C# | C Sharp for Loop
For loop is used to iterate a part of the code multiple times. We must use for loop instead of using while and do while if the number of iteration is known in advance. For loop in C# is same as it was In C and C++.
Syntax:
for(<initialization>;<condition>;<increment/decrement>) { //Code which is to be executed several number of times }C# for loop example:
using System; public class ForLoopExample1 { public static void Main (string[] args) { Console.WriteLine("Enter The number of which you want to print the table??"); int num=Convert.ToInt32(Console.ReadLine()); for(int i=1;i<=10;i++) { Console.WriteLine(num +"X" +i +"=" +num*i); } } }Output
Enter The number of which you want to print the table?? 6 6X1=6 6X2=12 6X3=18 6X4=24 6X5=30 6X6=36 6X7=42 6X8=48 6X9=54 6X10=60 C# nested for loop: Two loops get executed in nested for loop named as inner loop and outer loop. The inner loop iterates n number of times for each outer loop iteration. Syntax:
for(<initialization>;<condition>;<updation>) { for(<initialization>;<condition>;<updation>) { //some statements //the loop iterates until the inner condition fulfills for every outer loop execution }C# Nested for loop Example:
using System; public class Nested_For_Loop_Example2 { public static void Main (string[] args) { int row=Convert.ToInt32(Console.ReadLine()); for(int i=1;i<=row;i++) { for(int j=1;j<=i;j++) { Console.Write("*"); } Console.WriteLine(); } } }Output
Enter The Number of Rows 10 * ** *** **** ***** ****** ******* ******** ********* **********C# Infinite for loop: An infinite loop is the one which iterates infinite number of times. the for loop becomes an infinite loop if the condition provided is never going to be fulfilled.
C# infinite for loop Example:
If we put two semicolons only in for loop then the loop will iterate till infinite times. this is the simplest way to create an infinite for loop.
using System; public class InfiniteForLoopExample { public static void Main (string[] args) { for(;;) { Console.writeLine("this is an infinite loop"); } } }