The loops are used for repeating a statement or group of statement.
For Loop:
We need the following,to use this loop.
1.A starting value to initialize the loop.
2.A condition for running the loop.
3.An operation to update the loop.
Example:
static void Main(string[]args)
{
int i, num,sum;
sum=0;
for(i = 0; i < 5; i ++)
{
Console.WriteLine("Enter a number");
num = int.Parse(Console.ReadLine());
sum = sum + num;
}
Console.WriteLine("The sum of all the numbers is {0}", sum);
}
While Loop
The while loop is almost similar to the 'for loop' with some difference in the syntax.
Example:
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);
}