C++ Iterative statements(cont.)

We have already seen for loops. Now let us look at while loop and the do-while loop.

While loop

  • A while loop enables you to execute a block of code if a given condition is true.

  • It is like a repeating if statement.

  • It checks the condition before each loop.

  • The following code example shows how to use a while loop.

int n = 0;

while( n < 10 ) {

cout << “value of n: ” << n << endl;

n++;

}

  • The above code prints the value of n from 0 to 9. When n reaches 10, the condition is false and exits the loop.

  • If the counter value is not changed inside the while loop, then the loop will result in an infinite loop as the condition can never result in False.

 

Do-While loop

  • The Do-While loop is similar to a while loop except that a Do-While loop will execute the body of the loop at least once.

  • In a While loop, if the condition is false from start, then the loop will not execute.

int sum=0;

do {

cout<<“Enter any number less than 5: “;

cin>>number;

sum += number;

}while(sum<20);

 

  • The above do-while loop asks the user to enter a small number. This number is added to sum.This continues till sum is 20 or greater. When sum is 20 or greater, then control exits the loop.

  • Remember the semi-colon with ‘while’ in do-while loops. While loops do not have semi-colon with ‘while’.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: