Navigation

Shopping cart

There are no products in your shopping cart.

0 Items $0.00

Loops

Loops can occur in the Input Data, the Perform Calculations, and the Output Results section of your algorithm.

Types of Loops

Count Controlled Loops - Looping when you know exactly how many times your code must be repeated.

Sentinel Controlled Loops - Loop until a special value is input.

End of File Controlled Loops - Loop until the end of a file is found.

Flag Controlled Loops - Loop until some value is set to true (or perhaps set to false).

Loops in Input Data

Sometimes you need to make sure the user inputs valid data. Lets say that the user must input a number between 0.0 and 1.0. If they enter a value outside of this range, they should be prompted to re-enter the value.

  • input data
    • Loop until the user enters a value between 0.0 and 1.0

A common method to solve this problem looks like this:

  • Prompt the user to enter a value
  • Input the value
  • Loop if the value isn't valid
    • Display an error message
    • Prompt the user to enter a value
    • Input the value
  • End the loop

Translating it into C++ looks like this:

double value;

cout << "Enter a value between 0 and 1: ";

cin >> value;

while(value < 0.0 || value > 1.0)

{

cout << "Invalid value, must be between 0 and 1" << endl;

cout << "Enter a value between 0 and 1: ";

cin >> value;

}

Loops in Perform Calculations