The Do-While Loop
Source Code :
// Program Description:
// A Program that uses do-while iteration construct to print a series
#include<iostream.h>
#include<conio.h>
void main()
{
// cleaning the screen
clrscr();
// declaration of variables
int ctr = 0;
// do-while loop starts here
do
{
cout<<endl<<"\t"<<ctr;
ctr++;
} while(ctr<=5);
// do-while loop ends here
// waiting for the user to analyse the output
cout<<endl<<endl<<"\tPress any key to quit...";
getch();
}// main ends here
Program Flow :
This Iteration Construct is quite similar to the previously explained While Construct. But if you look closely you'll find one difference i.e. the keyword Do present in place of the While keyword and the While keyword has been moved to the end. This is no typo. It's actually the syntax of Do-While Construct. This construct is an exit-controlled loop i.e. the looping condition is checked at the end of each cycle. The inference that can be drawn is that the loop block will be executed at least once even if the condition is false in the first go. Therefore this kind of loop features an extra execution of the until and unless the correct guard code* is provided.
- The Block of code present inside the curly braces is executed.
- The Loop Statement checks the Counter's Value with the specified condition.
- If the Condition evaluates to true the compiler enters the Loop's body and executes the whole block again.
- Once the False condition is met the Compiler exit the Loop and moves on.
- The compiler then waits for the user to press any key to exit.
In the above example I have looped the block using the condition "Less Than or Equal To" which prevents the extra execution of the loop.
No comments:
Post a Comment