By 22/07/2015 11 Comments

C# Nested While Loops

  • Declaration of one or more while loops inside other while loop’s body is called nested while loops.
  • The while loop which is declared inside other while loop is called inner while loop.
  • Nested while loop is 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 while 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 sum with 0.
            int sum = 0;

            // Initialize an int type outerLoopNumber with 1.
            int outerLoopNumber = 1;

            while (outerLoopNumber <= 3)
            { // Outer while loop scope starts.

                // Initialize innerLoopNumber with value 1.
                int innerLoopNumber = 1;

                while (innerLoopNumber <= 3)
                { // Inner while loop scope starts.

                    // Add number 1 to sum variable each time.
                    sum += 1;

                    // Print sum variable.
                    Console.Write(" {0}", sum);

                    // Increment innerLoopNumber by 1 each time.
                    innerLoopNumber++;

                } // Inner while loop scope ends.

                Console.WriteLine();
                
                // outerLoopNumber variable will be incremented by 1 every time.
                outerLoopNumber++;

            } // Outer while loop scope ends.

            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 .