C Sharp

Nested Loops

In the embedded-statement of a for loop, you can also have other for loops, which are generally referred to as nested loops. Using the example from the previous section, I've added a nested loop that causes the application to print three characters per line, instead of one per line: -

using System;
class NestedForApp
{
    const int StartChar = 33;
    const int EndChar = 125;
    const int CharactersPerLine = 3;
    static public void Main()
    {
        for (int i = StartChar; i <= EndChar; i+=CharactersPerLine)
        {
            for (int j = 0; j < CharactersPerLine;  j++)
            {
                Console.Write("{0}={1} ", i+j, (char)(i+j));
            }
            Console.WriteLine("");
        }
    }
}

Note that the variable i that was defined in the outer loop is still in scope for the internal loop. However, the variable j is not available to the outer loop.