C# While Loop
If we want some operations to repeat depending on a condition, we can use the while loop. A condition is specified in the first line of the while loop. As long as this condition is met, we write the operations we want to be done inside the loop.
When using a for loop, the number of times the loop will return is known from the beginning, or at least it can be predicted.
The while loop is preferred when it is not possible to predict how many times the loop will loop. If the condition specified at the beginning is not met, the loop may not return at all, and if it does, it may return many times.
while (our condition)
{
operations that will be repeated as long as conditions hold...
}
A counter is not kept and incremented as in the for loop. If we need a variable that is constantly increasing or decreasing, such as a counter, we must define it ourselves and do the increase/decrease ourselves.
Also, the loop must be designed to end somewhere. In other words, we must determine the condition we wrote in such a way that the condition does not come true somewhere and the cycle ends. Otherwise, it enters an infinite loop.
While Loop Example
The program that continues to ask for numbers until the user enters 0, adds the entered numbers to the total, ends the loop when he enters 0 and writes the total to the screen:
int sum=0, count=1;
while(number != 0)
{
Console.Write("Number: ");
number = int.Parse(Console.ReadLine());
total += number;
}
Console.WriteLine(total);
Console.ReadKey();
Here initially sai variable 0 from an error made is to avoid the process variable with an empty value if a different reason for making our cycle is reached. The initial value doesn't matter, as the number entered by the user is taken into the number variable as soon as you enter the loop.
This example we made with a while loop is actually more suitable for solving with a do-while loop. You can see the solution made with do-while in next pages.
C# Console While Loop tutorials, using while loop, difference between console while loop and for loop
EXERCISES
The program that continues to ask for numbers as long as the sum of the numbers entered by the user is less than 100, and then writes the number of attempts and the total to the screen:
int sum=0, count, counter=0;
while (total < 100)
{
Console.Write("Number: ");
number = int.Parse(Console.ReadLine());
total += number;
counter++;
}
Console.WriteLine(counter+ ".sum at trial= " + total);
Console.ReadKey();
Example of using while loop and counter
|
|
Let's write the program that asks the user for numbers 10 times and adds these numbers with a while loop:
int sum=0, count, counter=0;
while (counter < 10)
{
Console.Write("Number: ");
number = int.Parse(Console.ReadLine());
total += number;
counter++;
}
Console.WriteLine(total);
Console.ReadKey();
Read 764 times.