Home » C# Basics » 03 - C# Programming - Part 1
3
While Loop
Defines what the while-loop is and the conditions of its use in a C# program
The `while loop is almost similar to the `for' loop with some difference in the syntax:
initialize loop;
while (check condition)
{
//statements inside the loop
update loop
}
In a `while' loop, the initialization is done outside the loop and the updating is done inside the loop. Apart from these differences, the working of the `while' loop is similar to that of the `for' loop.
We can convert the example shown in the `for' loop using the `while' loop as shown in the following code:
static void Main(string[] args) { int i, num, sum;
sum = 0;
i = 0;
while(i < 5)
{
Console.WriteLine("Enter a number");
num = int.Parse(Console.ReadLine());
sum = sum + num; i++;
}
Console.WriteLine("The sum of all the numbers is {0}", sum);
}