For Loop
Defines the simplest kind of loop and its function in a C# program
The `for' loop is the most commonly used loop. To use this loop, we need the following:
- A starting value to initialize (start) the loop.
- A condition for running the loop.
- An operation to update the loop.
The syntax of the `for' loop is:
for(initialize loop; check condition; update loop)
{
//statements inside the loop.
}
Here is an example of the `for' loop:
int count, number;
number =1;
for(count=0;count<10;count++)
{
number=number+1;
}
In the example, the initial value of count is 0. This initial value is tested using the condition - count<10. Since the value of count is 0 and it is less than 10, the program will enter inside the loop and execute the statements here. Once all the statements inside the loop are executed, the program will increase the variable `count' by 1 (count++). Now the value of count is 1. This new value will again be tested using the condition. The condition is still true (1 is less than 10). Hence, the loop will execute once again.
When the value of count becomes 9, the loop will execute and then increase the count to 10. Now the condition will become false since 10 is not less than 10. Here, the loop will stop.
If we make a mistake in the initialization, the loop may not run. For example, if we initialize count with 10 instead of 0, the condition will become false very first time and the loop will not execute even once.
Similarly, if we forget to increment count, it will always remain 0. Now the loop will run forever because 0 is always less than 10 so the condition remains true. Such a loop is known as an infinite loop.
Let us create one more program using the `for' loop. Start a new console project. Type the following code inside the Main method:
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);
}
In this code, we have declared three integer variables - i (for the counting of loop), num (for entering values) and sum (for calculating the sum of all the input values). Inside the for loop, the first statement asks the user to enter a number. The second statement converts the input value into integer and assigns it to the variable num. The third statement adds the value of num to the variable sum (note that the initial value of sum is 0).
Since the loop will execute five times, the value entered by the user will be added to the previous value of the sum each time. At the completion of the loop, the variable `sum' will contain the sum of all the five values. An output statement then displays this sum to the user.
Save and run the program. A sample run is displayed below:
