Thursday, January 21, 2010

The difference while loop and do while loop

While loop and do while loop look the same, but actually they have a difference.
While loop will check the condition first, then execute the statement if the condition is true.
Do while loop will execute the statement once, no matter the condition is true or false.
After the statement is executed once, next the condition is checked. If the condition is true, the statement will be repeated as long as the condition is true.

Look at these two examples:

1. using while loop:

#include "iostream.h"
#include "conio.h"

void main()
{
int n, i=1;
clrscr();
cout<< "Enter end number: ";
cin>>n;

while (i< =n) {
cout<< "The number is: "<< i;
cout<< "\n";
i++;
}
getch();
}

2. using do while loop:

#include "iostream.h"
#include "conio.h"

main()
{
int n, i=1;
clrscr();
cout<< "Enter end number: ";
cin>>n;
do {
cout<< "The number is: "<< i;
cout<< "\n";
i++;
}while (i< =n);
getch();
}
See the result below:
1. When the program is run, if we enter a number higher than 1, for example number 4, while loop and do while loop have the same result.


2. If we enter a number lower than 1, for example number 0, while loop will not execute the statement and do not show any result


And do wile loop, will execute the statement once:



0 comments:

Post a Comment