do...while Loop

Like while loop, do...while is also used to do programs which have "repetition" in it, so you don't have to waste time as well as energy to write the same repetitive code.

BUT IF WE HAVE "while loop" THEN WHY "do...while" ?

As in "while loop" if the given condition is wrong then the loop doesn't execute itself even a single time, but if we need our compiler to execute the loop at least once then we use do...while loop which means that do...while loop will execute itself at least once whether the given condition is "right" or "wrong".

LOGO


Syntax: do{
              Statement 1; //Repetitive Statements 
              Statement 2;
                      :
              Statement n;
               } while(expression);

Working: 
Example
BASIC FLOW
  • First the compiler will go to "do".
  • Then it will execute each and every Statement present within the loop.
  • Then it will check the given condition / expression written inside "while".
  • If the given condition is wrong then the compiler will come out of the loop.
  • And if the given condition is right then the compiler will move back to do.

Some Examples of "do...while"
  1. To print "ProCoderMega" 10 times using "do...while loop".
    Example 1
    Example 1
    It will print "ProCoderMega" 10 times.
  2. To give the sum of first 5 whole no.s.
    Example 2
    Example 2
    The output is : 15

So what is the difference between while loop and do while loop
⇒while loop execute itself only when the condition is "True" whereas do...while execute itself at least once even the condition is "False".
In while loop first the condition is checked then the compiler move towards the "repetitive statements" but in the do...while loop first the repetitive statement is executed then the condition is checked.

Things To Remember 

  • do...while loop will get executed at least one time.
  • Here after while keyword their is a semi column ( ; ).
  • If  the number of times a program get executed in the while loop is "n" then the number of times the same program which is going to be executed by do...while loop is "n" too until and unless the given condition is false i.e, number of times both gets executed is same if the condition is true.
  • Condition is compulsory i.e, without the given condition the compiler will show "error".



Check out our post on while loop and for loop.



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