The placing of one loop inside the body of another loop is called nesting. When you “nest” two loops, the outer loop takes control of the number of complete repetitions of the inner loop. While all types of loops may be nested, the most commonly nested loops are for loops.
C# allows a for loop inside another for loop.
Example 1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | static void Main(string[] args) { //www.csharp-console-examples.com for (int i=1;i<=10;i++) { for (int j = 0; j <= 10; j++) { Console.WriteLine("{0}x{1} = {2}", i, j, i * j); } Console.WriteLine("===================="); } Console.ReadKey(); } |
Output:
Example 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | static void Main(string[] args) { //www.csharp-console-examples.com for (int j = 1; j <= 10; j++) { for (int i = 1; i <= 10; i++) { Console.Write("{0}*{1}={2}\t", i, j, (i * j)); } Console.WriteLine(); } Console.ReadKey(); } |
Output: