Repetition Control or Looping

Repetition Control, or "looping" allows a programmer to repeat a set of instructions in an efficient, logical way. Not only is it more efficient and time-saving, it allows a user to have control of exactly how many times the set of instructions is done. Thus, we gain two major goals of programming: efficiency of instruction and efficiency of memory-use.

There are three main loops used in C++: The "do-while " loop, the "while" loop and the "for" loop. All have particular uses, and each has its own advantage.


I) The do-while Loop

The C++ Do-While statement has the following form:


do

statement

while (expression);



#include <iostream.h>

int main( )

{

int time //counter variable

time = 1;

do

{

cout<<"Value of time="<<time<<"/n";

time++;

} while (time<=5);

cout<<"End of the Loop.\n"

}


Program Output:

Value of time = 1

Value of time = 2

Value of time = 3

Value of time = 4

Value of time = 5

End of the loop.


time = 1;

do

{

cout<<"Value of time ="<<time<<"/n";

time++;

}

while (time<=5);




Sentinel Loops

In the following program, the user is asked to enter a value that is less than 5 and repeats until the user complies:


#include<iostream.h>

main( )

{

double input; //user input number.

do

{

cout<<"Input a number less than 5";

cin>>input;

if (input>=5)

cout<<"That value was too large, try again.\n";

}

while(input >= 5);

cout<<"Thank you...\n";

}


II) The while Loop

The Structure of the while Loop

while (expression)

statement;


#include<iostream.h>

main( )

{

int time = 1; //counter variable.

while(time<=5)

{

cout<<"Value of time=" << time << "\n";

time++;

} //End of while.

cout<<"End of the loop.\n";

}


Program Output:

Value of time = 1

Value of time = 2

Value of time = 3

Value of time = 4

Value of time = 5

End of the loop.


time = 1;

while (time<=5)

{

cout<< "Value of time =" <<time<< "\n";

}




III) The for Loop

What the for Loop Looks Like

Four Major Parts:

1. The value at which the loop starts.

2. The condition under which the loop is to continue.

3. The changes that are to take place for each loop.

4. The loop instructions.

For(initial-expression; conditional-expression; loop-expression)

{loop instructions};


Example:

#include<iostream.h>

main( )

{

int time; //Counter variable.

//The loop starts here.

for(time = 1; time<= 5; time = time + 1)

cout << "Value of time =" << time <<"\n"; //The loop stops here.

cout<<"This is the end of the loop.\n";

}


Program Output:

Value of time = 1

Value of time = 2

Value of time = 3

Value of time = 4

Value of time = 5

This is the end of the loop.


for(time = 1; time<= 5; time = time + 1)

cout << "Value of time =" << time <<"\n";


Back to the Programming Section