Loops | Code Example

What is Loop?

Loop is a control flow statement that allows code to be executed repeatedly based on some given condition. Loops are a repeating IF statement. All Loops consist of a condition and a block of code to be executed if the condition is true.

Commonly used Loops

  • While Loop
  • Do While Loop
  • For Loop
  • Nested For Loop

Difference between ‘For Loop’ vs ‘While/Do’

For Loop Give and increment a variable automatically.

While/Do Do Not Give or increment a variable automatically.

Code Example | C#

    • While Loop

        public void practiceWhileLoop()
        {
            int x = 0;
            while (x < 5)
            {
                Console.WriteLine("The value of x is" + x);
                x++;
            }
        }
    • Do While Loop

        public void practiceDoWhileLoop()
        {
            int x = 0;
            do
            {
                Console.WriteLine("The value of x is" + x);
                x++;
            } while (x<10);
        }
    • For Loop

       public void practiceForLoop()
        {
            for (int x = 0; x<20; x++)
            {
                Console.WriteLine("The value of x is" + x);
            }
        }
    • Nested For Loop

        public void practiceNestedForLoop()
        {
            for (int x = 0; x < 10; x++)
            {           
                for(int y = 0; y <10; y++)
                {
                    Console.WriteLine( "(" + x + "," + y + ")" );
                }
            }
        }
Advertisements

Leave a Reply