Software & Finance





C# - Difference Between for, while and do while loop





The main difference between for loop, while loop, and do while loop is

  • While loop checks for the condition first. so it may not even enter into the loop, if the condition is false.
  • do while loop, execute the statements in the loop first before checks for the condition. At least one iteration takes places, even if the condition is false.
  • for loop is similar to while loop except that
    • initialization statement, usually the counter variable initialization
    • a statement that will be executed after each and every iteration in the loop, usually counter variable increment or decrement
    The following sample code explains all 3 different loops:

 

 

Source Code


using System;

using System.Collections.Generic;

using System.Text;

 

namespace Loops

{

   class LoopDifference

   {

      static void Main(string[] args)

      {

         const int MAX = 5;

         for (int i = 0; i < MAX; i++)

         {

            System.Console.WriteLine("For Loop : {0}", i);

         }

 

         int j = 0;

         while (j < MAX)

         {

            System.Console.WriteLine("While Loop : {0}", j);

            j++;

         }

 

         int k = 0;

         do

         {

            System.Console.WriteLine("Do While Loop : {0}", k);

            k++;

         } while (k < MAX);

      }

   }

 

}

Output


For Loop : 0

For Loop : 1

For Loop : 2

For Loop : 3

For Loop : 4

 

While Loop : 0

While Loop : 1

While Loop : 2

While Loop : 3

While Loop : 4

 

Do While Loop : 0

Do While Loop : 1

Do While Loop : 2

Do While Loop : 3

Do While Loop : 4

 

Press any key to continue . . .