Control statements- While and Do While - DotNet and DataBase

Sunday, 8 July 2018

Control statements- While and Do While





While loop is used to execute some piece of code for certain number of times. This loops will be executes until the condition becomes false.

Syntax
---------
while(condition) {
   statement(s);
}



Example
----------
namespace ControlStatements
{
    class Program
    {     
        static void Main(string[] args)
        {

            int i = 1;
            int k = 15;

            while (i <= k)
            {
                Console.WriteLine("i value is :" + i);
                i++;
            }
            Console.Read();
        }
    }
}



In the above example, I want to print numbers from 1 to 15.
So, I used while loop to get the expected output.

The same output we can get using for loop also. So, we should know the difference between for and while loops like where should we use for loop and while loop. This we will discuss the difference on the next post.


Do while:
-----------

Do while loop also to execute the piece of code for certain number of times.
But the difference is do-while will be executed at-least once even the condition is false.

do{
   statement(s);
}while(condition);


Example
-----------
namespace ControlStatements
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 1;
            int k = 15;
            do
            {
                Console.WriteLine("i value is :" + i);
                i++;
            } while (i < k);
            Console.Read();
        }
    }
}


Above code prints 1 to 14 numbers.

Let us suppose i=15 and k=15, in this case from the above logic, while loop prints null, but do-while prints 15.

Practice

No comments:

Post a Comment

x

Get Updates On

Discussion updates

Straight Into Your INBOX!

Enter your email address to subscribe to this website and receive notifications of new posts by email.