ANINDAM IT

SEO/SEM

C++ Loop

C++ - While Loops

Written by Gary Texmo

The while loop is almost exactly the same as the do loop except that its condition is tested at the start of the loop intead of at the end... and the format is slightly different. The easiest way to see this is simply to re-write the above example with a while loop.

#include <iostream.h>

int main(void) {

int x = 0;

int y = 0;

cout << "Please enter an integer between 1 and 10: ";

cin >> x;

cout << "You entered: " << x << endl << endl;

while ((x < 1) || (x > 10)) {

cout << "Please enter an integer between 1 and 10: ";

cin >> x;

cout << "You entered: " << x << endl << endl;

if ((x < 1) || (x > 10)) {

cout << "Your value for x is not between 1 and 10!"

<< endl;

cout << "Please re-enter the number!" << endl << endl;

}

 

}

cout << "Thank you for entering a valid number!" << endl;

return 0;

}

Note that since the condition is tested at the start, we have to prompt the user for a number before we start. Depending on the circumstance, we could arrange this loop in a more intelligent way. For instance, if we set the value of x to one that would make the loop execute as false the first time through, then it would work without gathering input before the loop. This is generally not a good idea though since we might have this code in a function and the variable in question might be an argument (more later on that if you don't understand it). A more accepted way of accomplishing our goal of laziness would be to use a sentinel. Usually a boolean (true or false) variable that we would set to false when the condition was not satisfied and set to true when it was. Then we can loop so long as our sentinel is false. Check it out.

#include <iostream.h>

int main(void) {

int x = 0;

int y = 0;

bool validNumber = false;

while (validNumber == false) {

cout << "Please enter an integer between 1 and 10: ";

cin >> x;

cout << "You entered: " << x << endl << endl;

if ((x < 1) || (x > 10)) {

cout << "Your value for x is not between 1 and 10!"

<< endl;

cout << "Please re-enter the number!" << endl << endl;

}

else

validNumber = true;

}

cout << "Thank you for entering a valid number!" << endl;

return 0;

}

So there you go, a sentinel lets us accomplish the same thing in less code (always a bonus). One last thing to note is that do and while loops can be nested just like for loops in the same way. Sometimes it's not apparent so I just thought I'd let you know.

In conclusion, loops are an easy way to execute the same block of code more than once. Very good for those nitty gritty repetative tasks that make programming so much fun. You might want to fool around with loops a little just to get a feel for them, but they are pretty simple and after seeing a few more applications of them, you'll have it down pat if you don't already.

 

 

Tutorial Info
Written By: Gary Texmo
Written For: Mike of
http://www.bluesfear.com

 

Back to Bluesfear
Digital Art

2000, 2004© BlueSfear

 

 

 

C++ Loops: Key Points

 

Three main types of loops in C++

1. while loop

 

This loop is used to execute a block of code as long as a boolean condition is true.

while (boolean expression)
       statement or compound statement

1. If the condition is initially false, the body of the loop is skipped
2. The elements of the condition must be modified in the loop, otherwise it will become infinite
3. Initialization of variables involved in boolean expression is usually required

Example: Counts down from 5 to 1

num=5;
while (num >=1)
    cout<<num--;    

Example:

more = true;
// loop keeps reading data and adding to total until a data value of -1 is reached
while (more)
{
    cout<<"Enter more data";
    cin>>data;
    total+=data;
    more = data <> -1
}

    

2. do loop

 

This loop is similar to the while loop, except the boolean expression is tested at the end of the loop instead of the beginning. The loop continues as long as the boolean expression is true.

do
    statement or compound statement
while (boolean expression)

1. Body of loop always executes at least once
2. The elements of the condition must be modified in the loop, otherwise it will become infinite
3. Doesn't always require initialization

Example: count down from 5 to 1
num=5;
do
    cout<<num--;
while(num>=1);

Example: (validating input)

cout<<"Enter a number between 1 and 10";
do
    cin>>num;
    error=(num<1) or (num>10);
    if (error)
         cout>>"Error - must be between 1 and 10 try again"
while (error);

3. for loop

 

This loop is more versatile than the other two loops. It has a format that offers a lot of flexibility

for (initialization; boolean expression; increment)
     statement or compound statement

1. initialization
2. repeat as long as boolean expression is true... <--continue condition!
2.1 .     do body of loop
2.2        increment

1. The initialization happen before the loop is first executed.
2. The boolean expression controls the loop. The loop executes as long as this expression is true. This expression may be simple or complex
3. The increment happens at the end of each cycle through the loop.
4. Loop body will be skipped if boolean expressions is false
5. All three parts of the for loop are optional!

Example: infinite loop

for(;;)
{
cout<<"hello"<<endl;
}

Example: condition only

for(;num<10;)
{
    num=rand()%20;
}

Example: multiple initializations

for (int x=1, int k=5; (x<k)||(k<10) ; k++,x+=2)
{
        cout<<"looping again..."<<endl;

}

Example: count from 5 to 1

for (int x=5; x>=1; x--)
    cout<<x;

Example: using boolean variable

for (int x=1; !done ; )
{
        ... do stuff
        ... set the done variable
}

 

Recent Videos

No recent videos