TechCognition

Microsoft Visual Studio 2017 Promo Code
Microsoft Office 2016 Promo Code

While and do-While Loops in C#

While and do-while loops are used to execute a sequence of statements repeatedly. In this article, we discuss what is the difference between while and do-while loops. 

While Loop:

By using While loop we can repeatedly execute statements till the expression mentioned in while statement is true. While loop first tests the expression before executing the statements inside the loop. 

Open Microsoft Visual Studio and create Console application; add below code. The code inside while loop executes till the variable n is less than 50. 

using System; 

namespace CSharpWhileDoWhile

{

    class Program

    {

        static void Main(string[] args)

        {

            int n = 0; 

            while (n < 50)

             {

                n = n + 1;

            } 

            Console.WriteLine("The value of variable n is: {0}", n);

            Console.ReadLine();

        }

    }

}

Run the application and displays the output as below. 

  

Do-while:

The do-while statement also works same as while statesmen, only the difference is do-while statement checks the condition after statements execution.  

using System; 

namespace CSharpWhileDoWhile

{

    class Program

    {

        static void Main(string[] args)

        {

            int n = 0; 

            do

            {

                n = n + 1; ;

            } while (n < 50); 

            Console.WriteLine("The value of variable n is: {0}", n);

            Console.ReadLine();

        }

    }

}

In do-while, statems executions happenes minimum one time because of do-while checs the condition after statements execution.
 

Add comment

Loading

© Copyright 2018 www.techcognition.com | Sitemap