C# For Loop


A for loop is a repetition control structure and the for loop is used for iterative purposes. if I want to repeat a certain set of statements for a particular number of times, eg I want to print numbers from 1-10 then we used for loop to print the number. The for loop executes a block of statements repeatedly until the specified condition returns false.


for (int a = 1; a < 10; a++)
{
    Console.WriteLine("Value of a is - " + a);
}

the flows of control in a for loop  −

  1. Initializer
  2. Condition
  3. Iterator

Initializer: The init step is executed first, and only once. The init is used to initialize a variable eg (int 1=1);.

Condition: The condition is a boolean expression that will return either true or false. if an expression evaluates to false the loop is exited otherwise, it will execute the loop again. eg(i<10)

Iterator: The iterator defines the incremental i++ or decremental i-- of the loop variable i.e i++ or i--


for (int a = 1; a < 10; a++)
{

}


using System;					
public class Program
{
	public static void Main()
	{
		for (int a = 1; a < 10; a++)
		{
			Console.WriteLine("Value of a is - " + a);
		}
	}
}

Output


Value of a is - 1
Value of a is - 2
Value of a is - 3
Value of a is - 4
Value of a is - 5
Value of a is - 6
Value of a is - 7
Value of a is - 8
Value of a is - 9

Code Explanation

  1. The 'for' keyword is used to start the for loop statement
  2. In the 'for loop', we define 3 things. The first is to initialize the value of a variable which is int a=1 , which will be used in the 'for loop'.
  3. The second is to compare the value. it will compare the value (a<10) The condition is a boolean expression that will return either true or false. if an expression evaluates to false the loop is exited otherwise, it will execute the loop again;
  4. Finally, we increment the value of 'a' accordingly.