For Loop

In this lession you will learn how to execute a statement or code block multiple times using loop in C#. We will also see the structure of "for" loop, how to write nested "for" loop and on some specific condition control the flow of executions.

C# has keyword called "for" which indicates loop. C# calls repetadly code block inside the "for" loop till given condition evaluates false.

When you know excact number of times you want to call your code block then for loop can be used rather than while loop.


Try it
for (initialisation; condition; iterator)
	//code block to execute multiple times

for loop has three optional part seperated by semicolon as below

initialisation: Initilizer is the first section in syntax, where we will initialise loop local variable and it cannot be accessed outside the loop. If we want to start the loop from 0 then we will initialise loop variable with 0 value.

condition:Condition is the second part of the "for" loop where we will define the condition to check whether it's true or false. This section will be called before executing the code block, if condition is true then code block will be executed else control will transer to the next immediate statement outside the loop.

iterator:Iterator is the last section of the "for" loop where we can increase or decrease the value of initialised variable in the first section.

C# For Loop Example

Try it
for (int loop = 1; loop < 6; loop++)
    Console.WriteLine("For loop iteration:{0}", loop);
// Output
For loop iteration:1
For loop iteration:2
For loop iteration:3
For loop iteration:4
For loop iteration:5

C# Nested For Loop

When we are using a loop inside another loop then it is called nested loop. For example

Try it
for (int outerloop = 0; outerloop < 5; outerloop++)
    for (int innerloop = 0; innerloop <= outerloop; innerloop++)

In the above example we have used nested "for" loop. First loop will iterate till 5 number and innerloop will iterate till the value of outerloop variable value, and at the end of the program output will be printed as nice triangle. If you see carefully inside the inner loop we have used Console.Write method instead of Console.WriteLine.

C# Infinite For Loop

In for loop, since all the sections are optional that's why we need to be very carefull while declaring loop, otherwise it will become an infinite loop which will never complete and we need to terminate the program explicitly.

Try it
for (int i=1;  i >=0; i++)
It will print 111111111 and so on, it will never end.


← Previous

Next →