- What is for loop in C#?
- What is nested for loop in C#?
- How to use for loop in C# programming?
for loop is another powerful loop construct in C#. It is powerful and easy to use. for loop includes all three characteristics as initialization, termination and increment/decrement in a single line.
for (initialization; termination; increment / decrement) ;
Example:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace for_loop { class Program { static void Main(string[] args) { int i; for (i = 0; i < 5; i++) { Console.WriteLine("For loop Example"); } Console.ReadLine(); } } }
Output
For loop Example
For loop Example
For loop Example
For loop Example
For loop Example
__
Nested for loop
Sometimes, you are required to perform a task in nested loop condition. A loop within a loop is called nested loop. You can nested n number of loop as nested.
Example:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace nested_loop { class Program { static void Main(string[] args) { int i, j; for (i = 1; i <= 5; i++) { for (j = 1; j <= i; j++) //Nested for loop { Console.Write(j); } Console.Write("\n"); } Console.ReadLine(); } } }
In the preceding example, the outer for loop won’t increment until inner for loop processes it’s all the cycles. Once the condition of inner for loop becomes false, the outer for loop increment by one and then again inner for loop does same work as previous.
Output
1
12
123
1234
12345
__
Summary
In this chapter you learned what is for loop and how to use it in program. You also learned what is nested for loop and its implementation in C# programming. In next chapter you will learn about foreach loop in C#.