Topic : While Loop in C# Programming:



While Loop:

A while loop statement repeatedly executes a target statement as long as a given condition is true. in a while loop, a Boolean expression is evaluated. if the expression in the while statement is true, the resulting action, called loop body (which can be a single statement or a block of statements) executes, and the Boolean expression is tested again. if it is false, the loop is over, and program execution continues with the statement that follows the while statements. the cycle of execute-test-execute-test continues as long as the Boolean expression continues to be evaluated as true as shown in figure.



while Loop

Syntax:

The Syntax of the while-loop is:



while ( condition )
{
	/*Block of one ore more Csharp statements to be 
	  execute if the condition is true. */
}



The Parentheses around "condition" are required. as long as "condition" is True, the block of one or more C# statements executes repeatedly until Condition become False. Braces are required before and after the body of the while-loop, unless we want to execute only one statement. Each statement in the body of the while-loop requires are ending semicolon.

The Placeholder "condition" usually contains relational, and possibly logical, Operators. These operators provide the True-False condition checked in "Condition" if "Condition" become false at starting of while -loop, the body of while-loop does not execute at all, because first "condition" will be tested, if condition is TRUE, the loop-body will be execute, else there is Nothing to execute in the loop-body if condition Become FALSE.



If the body of while-loop contains only one statement, the braces surrounding it are not required but it is good programming practice to enclose all while-loop statements in braces.


Example:

Let's have an simple example to understand how while-loop work.
In this example, we will create a simple Game. we will hide a number here, and can ask to our friend to Guess the number. This loop will be execute repeatedly until your friend Guess the right Number.



/*Example: While Loop: InfoBrother*/

using System;

namespace whileLoop
{
    class Program
    {
        static void Main(string[] args)
        {
            int number = 21; //this number need to be guess.
            int guess;   //will use to store user guess.

            Console.WriteLine("Enter Your Guess: ");
            guess = Convert.ToInt32(Console.ReadLine());


            //continue this loop till user enter 21.
            while(guess != number)
            {   //loop body begin.

                Console.WriteLine("Guess again...");
                guess = Convert.ToInt32(Console.ReadLine());

            }   //loop body close.


            /*when user will enter right guess. this statement will
              execute. */
            Console.WriteLine("You Enter Right Guess... Congrats:");
            Console.ReadKey();
        }
    }
}


Example:

let's have another useful example: in this example, the program will ask to enter UpperLimit (any number ) and will add these all number till Upperlimit and give you the sum. For example: if you enter "5" as an upperLimit, then it will add 0+1+2+3+4+5 and give you the sum (i.e. 15). it will start from 0 and will end at upperLimit.



/*Example: While Loop: InfoBrother*/

using System;

namespace whileLoop
{
    class Program
    {
        static void Main(string[] args)
        {
            int upperLimit;  //to get the limit from user.
            int sum = 0;     //to return sum.
            int number = 0;  //numbers < upperLimit

            Console.WriteLine("Enter Upper Limit value:");
            upperLimit = Convert.ToInt32(Console.ReadLine());


            //Loop will add the Numbers, until reach at upperlimit.
            while(number < upperLimit)
            {
                number = number + 1;  //increment number one by one.
                sum = sum + number;  //sum = 0 +1=1; -> 1+1=2 and so on.
            }


            //when program will reach at upperLimit, it will execute this statement.

            Console.WriteLine("The Sum of first {0} Numbers are: {1}", upperLimit, sum);

            Console.ReadKey();
        }
    }
}


Infinite Loop:

Be careful while using Loop. by using wrong condition, we can face an infinite loop. always select an limit for the loop, else condition of the loop will always true and become an infinite loop. Here is an example, Copy and paste this code into your compiler and check How infinite loop work. in this Example Program will ask to Enter the Starting Number. you can put any Number. and Loop will become Infinite Loop. because the condition is " Number > 0 " Obviously all positive Numbers are greater than 0. so there is No limit to terminate the Program. so the condition will always true and program will always continue.



/*Example: Infinite While Loop: InfoBrother*/

using System;

namespace whileLoop
{
    class Program
    {
        static void Main(string[] args)
        {
            int number = 0;

            Console.WriteLine("Enter the Starting number to Begin Loop: ");
            number = Convert.ToInt32(Console.ReadLine());

            //while number is greater than 0, mean no limit
            while(number>0)
            {
                Console.WriteLine("{0} , ", number);
                ++number;
            }

            Console.ReadKey();
        }
    }
}


Any C# expression can be placed inside the required parentheses in the while statement. As with the if statement, if the expression evaluates to false or zero, then the loop body is not entered. If the expression within the parentheses evaluates to true or any non-zero value, the loop body executes. With a while statement, when the expression is evaluated as true, the statements that follow execute repeatedly as long as the expression remains true.

















I Tried my Best to Provide you complete Information regarding this topic in very easy and conceptual way. but still if you have any Problem to understand this topic, or do you have any Questions, Feel Free to Ask Question. i'll do my best to Provide you what you need.

Sardar Omar.
InfoBrother





WRITE FOR INFOBROTHER

Advertising






Advertisement