Section 2 - Loops

spiral clock

4A.2.1 The Loop Concept

A loop does a statement (or block of statements) zero or many times, depending on the values controlling it. The part of the statement that manages the number of iterations of the loop is called the loop control. The statement, or block of statements, that is repetitively executed is called the loop body. The general form is

<loop control>
<loop body> ;

If the loop body contains more than one statement, you must enclose all the statements in braces like so:

<loop control>
{
<body statement>;
<body statement>;
<body statement>;
<body statement>;
<body statement>;
}

It is very important to indent the loop body. The compiler doesn't care, but we humans do. It makes it easy to see which and how many statements of the loop body are controlled by the loop control.  You will lose points if you forget to indent a loop body.

4A.2.2 Simple For Loops

If we wanted to count to 10, printing each number as we went, a for-loop would do the job:

int k;

for (k = 1; k <= 10; k = k + 1)
cout << "k = " << k;

The explanation of this loop is what you would expect. The top line is called the loop control.

The loop control says

When the loop ends, the program executes the next statement after the loop body. 

Guess, then confirm by running for yourself, what the output of the above loop looks like.

This for loop is good if you know, beforehand, how many times something will be repeated.  If the number of times that something is to be repeated is determined based on user input or other factors known only at run time, then a while loop is preferred.

Assignment #2 is a great opportunity to make for loops simplify our work.  For example, if I had said, "add all the odd numbers from 15 to 1001," then you should be able to do it simply with a loop rather than having one of those really long statements like 15 + 17 + 19 + ...  (sigh)  ... + 999 + 1001.  Give it a shot on your own.   Then compare with my solution:

#include <iostream>
using namespace std;

int  main()
{
// make these symbolic constants so that if we wish to change them
// we can do it quickly up here rather than muck around in the code
int const LOW_VAL = 15;
int const HIGH_VAL = 1001;

int sum;    // holds the answer
int k;      // loop counter

sum = 0;    // start it off at 0 - we will add to it
// loop, adding the ODD numbers
for ( k = LOW_VAL; k <= HIGH_VAL; k = k + 2 )
sum = sum + k;

cout << "The sum of the odd numbers between " << LOW_VAL
<< " and " << HIGH_VAL << ", inclusive, is " << sum << endl << endl;

return 0;
}

/* ------------------- Sample Run --------------------

Run the program to get the answer!

4A.2.3 While Loops - A Closer Look

Simpler than for loops, while loops are used when you don't have so much bookkeeping to do. The for loop had three control sections:  init, test, iteration.  The while loop only has one, the test. The idea is that you test the condition in the while statement.  If it is true, you do the loop one more time, and test again after each loop pass.  As long as the condition is true, you keep on looping.  If it ever becomes false, you end the loop and move on to the statement following the loop body

In the following excerpt from a program we ask the user for a value.  If they give us a number less than 20 we slap their wrists and ask again.  When they finally follow instructions, we leave them alone and end the input loop:

double withdrawal;

// get the withdrawal amount from user
cout << "Amount of withdrawal ($20 minimum): ";
cin >> withdrawal;

// trap user until they follow directions
while (withdrawal < 20)
{
cout << "$20 Minimum.  \nPlease try again: ";
cin >> withdrawal;
}
   
/* -------------------

Amount of withdrawal ($20 minimum): 18
$20 Minimum.
Please try again: 25

New balance:975.03

... etc.

------------------- */

This example was obviously not a complete program but merely a code fragment.  It demonstrates a while loop, and also gives a reasonable input filter on which you can base future assignments.  An input filter is a chunk of code that traps the user until he follows directions. But be careful:  We don't always want to trap the user into giving us a value with such a strict loop.  Often we want an escape so the user can quit gracefully after he sees what kind of "crazy" number we are asking him to enter.  This normally entails a slightly different logic.

Here is another example that shows a complete program. This is a guessing game.  The program asks the user to keep guessing until he gets it right.  This is an ideal situation for while loop - we don't know how many times the loop will go.  If we did, we would be using a for loop.  The spec is :

Write a program that produces some int using a calculation, and do so in a manner that will make it difficult for even the programmer to know (or guess) what int will result from this calculation.  Then, enter a loop that asks the user to guess the number.  If the user guesses too low, tell him "too low", and if he guesses high, tell him "too high", and then allow him to guess again.  When the user guesses correctly, congratulate him and end the loop.

See if you can write this program first.  Then, look at the answer.  I expect you to run this program and make it work.  If you can't, then ask me.  Otherwise, be prepared to tell me what the secret value is when you have a question about the next assignment!

#include <iostream>
#include <string>
using namespace std;

int  main()
{
// secret value - obfuscate so the programmer doesn't even know it
int const secretValue = (25 * 9801/35 - 200) / ( 25 + 34/12 );

// non constant variables
int guess;
bool correct; // loop control

// welcome message
cout << "Try to guess the secret value ... " << endl;

// now prepare to loop for the game
correct = false;  // this gets us into the loop

// loop as long as we are NOT correct
while ( !correct )
{
cout << "Your guess: ";
cin >> guess;
if (guess == secretValue)
{
// they got it.  wish them well and set loop control variable
cout << "Congratulations!!" << endl;
correct = true;  // this will end the loop next time we test
}

else if (guess < secretValue)
cout << "Too low.  Guess higher" << endl;
else
cout << "Too high.  Guess lower" << endl;
}

return 0;
}

/* ------------------- Sample Run --------------------
Try to guess the secret value ...
Your guess: 25
Too low.  Guess higher
Your guess: 90000
Too high.  Guess lower
Your guess: 5000

// THE RUN CONTINUES UNTIL THE USER EVENTUALLY GUESSES CORRECTLY WHEN ...

Congratulations!!
Press any key to continue . . .
---------------------- End Sample Run ---------------- */

The above examples will give you plenty of practice so you can write simple loops in real programs.  Try a few easy examples of your own.