While Loop

While loop is used in a program  to do the work which contains repetition. For eg: If you have to print the numbers from 1-100 then it will be harder to write the code for printing the statement 100 times. In that type of case we use loops and one of the loop is while loop.

Logo

Syntax: while(expression){
              Statement 1;  // Repeated Action
              Statement 2;
                      :
              Statement n;
            }

Working: 
  • First the compiler check whether the condition / expression is correct or not.
  •  If not then it will move to the very next line where the while loop is closed.
    Example 1
    Example 1
  • If the condition is true then the compiler moves inside the loop.
  • It will execute each and every statement inside the loop and at the end the compiler will again move to the condition of while loop.
    Example 2
    Example 2
  • Break statement or Update statement should be used inside the loop to make the given condition false at one moment, if not the loop becomes infinite.

   Some examples of "while loop"

  •    To print 10 times "Program".(Exit statement is Update statement)
    Example 3
    Example 3
    Here the program print "Program" 10 times.
  • To print "Code" if n > 10 or print "Dong" if n<10.(Exit statement is break statement)
    Example 4
    Example 4
    Since "if statement" is false so the compiler move to "else statement" where the break statement is written so the compiler will come out of the loop.
    So the OUTPUT is - DONG

Things To Remember

  1. If the condition is false then while loop doesn't execute itself and jumps to very next statement after it.
  2. Condition is compulsory in the case of while loop, you can't leave it.
  3. If no exit condition is written inside the loop then the loop becomes Infinite loop.
  4. Exit condition can be written in the form of "Update Statement" or "Break Statement".
Check out our post on do...while loop and for loop.

Check out our different post to get more concept.

For giving some suggestion please check our "Contact us" page. Also more update related to coding will be added in this Blog later on, so please get attached with this Blog. Thank you for your support and time...

Post a Comment

0 Comments