Kamis, 12 Januari 2012

Repetition Statement: The Do-While Loop in c++



We have already gone through The While Loop and The For Loop. Now its time for The Do-While Loop.

// Program 1

#include

using namespace std;

int main ()
{
int i = 0;
do
{
cout << i << endl;
i++;
} while (i < 10);
return 0;
}

The do-while loop works just like the for loop and while loop but with one exception. Unlike the for loop and while loop, the do-while loop will execute at least once.
The for loop and the while loop checks the condition and then the body of loop executes but in case of do-while, the body is executed first and then it checks the condition.


// Program 2

#include

using namespace std;

int main ()
{

    // The while loop
int i = -1;
while (i != -1)
{
cout << "Inside the while loop. " << endl;
cout << "Please enter a number or -1 to quit: ";
cin >> i;
}

    // The for loop
int j = -1;
for (; j != -1; )
{
cout << "Inside the for loop. " << endl;
cout << "Please enter a number or -1 to quit: ";
cin >> j;
}

    // The do-while loop
int k = -1;
do
{
cout << "Inside the do-while loop. " << endl;
cout << "Please enter a number or -1 to quit: ";
cin >> k;
} while (k != -1);

    return 0;
}

When you run the above program, only the body of do-while gets executed and others do not. The initial value is set to -1 and the condition is such that the value should not be equal to -1. The for loop and while loop checks the condition first and hence their body is not executed, the do-while loop executes the body first and hence it gets executed even though the condition is false, as it checks the condition after executing the body.

Use Do-While when you want the body of the loop to execute at least once, even if the condition is false at the start or else you could make use of the for loop and while loop.


Please do comment if you don't understand any part or want to know more or just want to say thanks. I love programming and love to teach my friends. Your suggestions and appreciation will make this blog much better.


View the original article here



Peliculas Online

0 komentar:

Posting Komentar