By 22/07/2015 12 Comments

C# Nested For Loops

  • Declaration of one or more for loops inside other for loop’s body is called nested loops.
  • The for loop which is declared inside other for loop is called an inner for loop.
  • Nested for loops are very useful for creating programs which has more than one dimensions such as rows and columns, a basic calculator layout, different shapes etc.
  • Using nested for loops we can access multidimensional array’s elements easily.
  • Nested loops are used for complex programs.

Example:

using System;
namespace csharpBasic
{
    // Start class definition / declaration.
    class Program
    {
        // Static main method void type declaration.
        static void Main(string[] args)
        {
            // initialize an int type variable sum with 0.
            int sum = 0;

            /* Following is for loop declaration, 
               this loop is called an outer loop,
               execute this loop 3 times according to its condition part.
             */
            for (int outerNumber = 1; outerNumber <= 3; outerNumber++)
            {   // starting outer loop scope.

                /* Following loop is called inner loop 
                   which is declared in outer loop’s body and 
                   according to condition this is also executed 3 times. 
                 */
                for (int innerNumber = 1; innerNumber <= 3; innerNumber++)
                {   // start inner loop scope

                    /* At every execution of inner for loop, 
                       1 will be added to sum variable. 
                       NOTE: this process continuous as is until inner loop’s condition becomes false 
                       and this inner loop depends on outer loop, 
                       so this inner loop always executed until outer loop becomes false.
                     */
                    sum += 1;
                    
                    // Print sum variable.
                    Console.Write(" {0}", sum);

                }   // End inner loop scope.

                /* When inner loop becomes false, 
                   than a new line will be created every time.
                 */
                Console.WriteLine();

            }   // End outer loop scope.
            Console.ReadKey();

        } // End of main method definition. 
    } // End of class. 

    /*
   The Output will be:
    1 2 3
    4 5 6
    7 8 9
  */
}





Next Tutorial →


← Previous Tutorial


Posted in: C# Basics, C#.NET

Leave your valuable Comment

Have a natural attraction for women cosmetics and replica watches uk clothes, no
more than two for men the most attractive one, is to make their own driving experience, happy and can serve as the facade of the car, another is to highlight the taste edify sentiment rolex replica watch. The replica rolex is undoubtedly the most fashionable accessories, wear a suit to attend the activities, but also get a decent match on the replica watches .