In c#, for loop is useful to execute a statement or a group of statements repeatedly until the defined condition returns true.
Generally, for loop is useful in c# applications to iterate and execute a certain block of statements repeatedly until the specified number of times.
Syntax
Following is the syntax of defining for loop in c# programming language.
for (initialization; condition; iterator) { // Statement(s) to Execute }
How he above for loop works?
C# for loop has three statements: initialization, condition and iterator.
The initialization statement is executed at first and only once. Here, the variable is usually declared and initialized.
Then, the condition is evaluated. The condition returns either true or false.
If the condition is true:
The statements inside the for loop are executed.
Then, the iterator statement is executed which usually changes the value of the initialized variable.
Again the condition is evaluated.
The process continues until the condition is evaluated to false.
If the condition is false, the for loop terminates.
Examples
using System; public class Program { public static void Main() { for (int i = 1; i <= 5; i++) { Console.WriteLine("Number i = : {0}", i); } Console.WriteLine("Press Enter Key to Exit.."); Console.ReadLine(); } }
Which will display the following
Number i = : 1 Number i = : 2 Number i = : 3 Number i = : 4 Number i = : 5 Press Enter Key to Exit..
break
using the break keyword we can stop the execution of for loop statement
Here is an example
using System; public class Program { public static void Main() { for (int i = 1; i <= 5; i++) { if (i == 3) break; Console.WriteLine("Number i = : {0}", i); } Console.WriteLine("Press Enter Key to Exit.."); Console.ReadLine(); } }
When you run the following you will see this displayed
Number i = : 1 Number i = : 2 Press Enter Key to Exit..
nested for loop
You can nest for loops, like this
using System; public class Program { public static void Main() { for(int i=1;i<=2;i++) { for(int j=1;j<=5;j++) { Console.WriteLine(i+" "+j); } } } }
When you run this, you will see something like this
1 1 1 2 1 3 1 4 1 5 2 1 2 2 2 3 2 4 2 5
No initialization and iterator statements
You can have a for loop without initialization and iterator statements, here is an example of this
using System; public class Program { public static void Main() { int i = 1; for ( ; i<=5; ) { Console.WriteLine("Iteration {0}", i); i++; } } }
You will see the following when this is run
Iteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5
Infinite Loop
If the condition parameter in for loop always returns true, the for loop will be infinite and runs forever. Usually this is a bug.
This would do this, i do not recommend running this.
using System; public class Program { public static void Main() { for (int i = 1; i > 0; i++) { i++; Console.WriteLine("i value: {0}", i); } Console.WriteLine("Press Enter Key to Exit.."); Console.ReadLine(); } }