Chapter 4: Looping
Resource: Starting Out with C++, Third Edition, Tony Gaddis
5.1  The Increment andDecrement Operators
++ and -- are operators that add andsubtract one from their operands.
num = num + 1;
num += 1;
num++;
Resource: Starting Out with C++, Third Edition, Tony Gaddis
Using ++ and -- inMathematical Expressions
a = 2;
b = 5;
c = a * b++;
cout << a << “   “  << b << “   “  << c;
 
Results:   2   6   10
Resource: Starting Out with C++, Third Edition, Tony Gaddis
Using ++ and -- in RelationalExpressions
x = 10;
if ( x++ > 10)
cout << “x is greater than 10.\n”;
Two operations are happening:
the value in x is tested todetermine if it is greater than 10
then x is incremented
Resource: Starting Out with C++, Third Edition, Tony Gaddis
5.2Introduction to Loops -The while Loop
loop is part of a program thatrepeats.
while loop is a “pre test” loop - theexpression is tested before the loopis executed
while (expression)
   statement;
Resource: Starting Out with C++, Third Edition, Tony Gaddis
5-3 Program
// This program demonstrates a simple while loop.
#include <iostream.h>
void main(void)
{
int number = 0;
 cout << "This program will let you enter numberafter\n";
cout << "number. Enter 99 when you want to quit the";
cout << "program.\n";
while (number != 99)
cin >> number;
}
Resource: Starting Out with C++, Third Edition, Tony Gaddis
5-3 Program Output withExample Input
  This program will let you enter numberafter number. Enter 99 when you want toquit the program.
 1 [Enter]
 2 [Enter]
30 [Enter]
75 [Enter]
99 [Enter]
Resource: Starting Out with C++, Third Edition, Tony Gaddis
Terminating a Loop
loop that does not have a way ofstopping is called an infinite loop:
int test = 0;
while (test < 10)
    cout << “Hello\n”;
A null statement is also an infinite loop, butit does nothing forever:
while (test < 10);
Resource: Starting Out with C++, Third Edition, Tony Gaddis
5.3Counters
A counter is a variable that isincremented or decremented eachtime a loop iterates.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
5-4 Program
// This program displays the numbers 1 through 10
// and their squares.
#include <iostream.h>
void main(void)
{
int num = 1;      // Initialize counter
cout << "number     number Squared\n";
cout << "-------------------------\n";
while (num <= 10)
{
cout << num << "\t\t" << (num * num) << endl;
num++;       // Increment counter
}
}
Resource: Starting Out with C++, Third Edition, Tony Gaddis
5-4 Program Output
number     number Squared
-------------------------1               12               43               94               165               256               367               498               649               8110              100
Resource: Starting Out with C++, Third Edition, Tony Gaddis
5.4   Letting theUser Control the Loop
We can let the user indicate thenumber of times a loop shouldrepeat.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
while (count++ < numStudents)
{
int score1, score2, score3;
float average;
cout << "\nStudent " << count << ": ";
cin >> score1 >> score2 >> score3;
average = (score1 + score2 + score3) / 3.0;
cout << "The average is " << average <<".\n";
}
5-6 Program
Resource: Starting Out with C++, Third Edition, Tony Gaddis
5-6 Program Output withExample Input
This program will give you the average of three testscores per student.
How many students do you have test scores for? 3 [Enter]
Enter the scores for each of the students.
Student 1: 75 80 82 [Enter]
The average is 79.
Student 2: 85 85 90 [Enter]
The average is 86.67. 
Student 3: 60 75 88 [Enter]
The average is 74.33.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
5.5Keeping a Running Total
running total is a sum of numbersthat accumulates with each iterationof a loop.
The variable used to keep therunning total is called anaccumulator.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
while (count++ < days)
{
float sales;
cout << "Enter the sales for day " << count<< ": ";
cin >> sales;
total += sales;
}
cout.precision(2);
cout.setf(ios::fixed | ios::showpoint);
cout << "The total sales are $" << total << endl;
}
5-7 Program Continued
Resource: Starting Out with C++, Third Edition, Tony Gaddis
5-7 Program Output withExample Input
For how many days do you have salesfigures? 5 [Enter]
Enter the sales for day 1: 489.32 [Enter]
Enter the sales for day 2: 421.65 [Enter]
Enter the sales for day 3: 497.89 [Enter]
Enter the sales for day 4: 532.37 [Enter]
Enter the sales for day 5: 506.92 [Enter]
The total sales are $2448.15
Resource: Starting Out with C++, Third Edition, Tony Gaddis
5.6Sentinels
sentinel is a special value thatmarks the end of a list of values.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
while (points != -1)
{
count++;
cout << "Enter the points for game " <<count << ": ";
cin >> points;
if (points != -1)
total += points;
}
cout << "The total points are " << total <<endl;
}
5-8 Program Continued
Resource: Starting Out with C++, Third Edition, Tony Gaddis
5-8 Program Output withExample Input
Enter the number of points your team hasearned so far in the season, then enter -1 when you are finished.
Enter the points for game 1: 7  [Enter]
Enter the points for game 2: 9  [Enter]
Enter the points for game 3: 4  [Enter]
Enter the points for game 4: 6  [Enter]
Enter the points for game 5: 8  [Enter]
Enter the points for game 6: -1  [Enter]
The total points are 34
Resource: Starting Out with C++, Third Edition, Tony Gaddis
5.7The do-while Loopand For Loops
In addition to the while loop, C++also offers the do-while and forloops.
do-while loop is similar to a whileloop, but in post-test format:
do
    statement;
while (expression);
Resource: Starting Out with C++, Third Edition, Tony Gaddis
5-9 Program
// This program averages 3 test scores. It repeats as many
// times as the user wishes
#include <iostream.h>
void main(void)
{
int score1, score2, score3;
float average;
char again;
do
{
cout << "Enter 3 scores and I will average them: ";
cin >> score1 >> score2 >> score3;
average = (score1 + score2 + score3) / 3.0;
cout << "The average is " << average << ".\n";
cout << "Do you want to average another set? (Y/N) ";
cin >> again;
} while (again == 'Y' || again == 'y');
}
Resource: Starting Out with C++, Third Edition, Tony Gaddis
 5-9 Program Output withExample Input
Enter 3 scores and I will average them:
80 90 70 [Enter]
The average is 80.
Do you want to average another set? (Y/N)
y [Enter]
Enter 3 scores and I will average them:
60 75 88 [Enter]
The average is 74.333336.
Do you want to average another set? (Y/N)
n [Enter]
Resource: Starting Out with C++, Third Edition, Tony Gaddis
The for Loop
Ideal for situations that require acounter because it has built-inexpressions that initialize andupdate variables.
for (initializationtestupdate)
   statement;
Resource: Starting Out with C++, Third Edition, Tony Gaddis
5-11 Program
// This program displays the numbers 1 through 10and
// their squares.
#include <iostream.h>
void main(void)
{
cout << “Number     Number Squared\n";
cout << "-------------------------\n";
 
for (int num = 1; num <= 10; num++){
cout << num << "\t\t" << (num * num) << endl;}
}
Resource: Starting Out with C++, Third Edition, Tony Gaddis
5-11 Program Output
Number     Number Squared
-------------------------1               12               43               94               165               256               367               498               649               8110              100
Resource: Starting Out with C++, Third Edition, Tony Gaddis
5.8Other Forms of theUpdate Expression
Incrementing the counter by somethingbesides 1:
for(number = 2; number <= 100; number +=2)
cout << number << endl; // print the even numbers 2 –100
Going backwards:
for(number = 10; number >= 0; number--)
cout << number << endl; //count from 10 to 0
A stand-alone for loop:
//This one prints the integers from 1 to 10
for(number = 1; number <= 10; cout << number++)
There are quite a few variations, try some ofyour own!
Resource: Starting Out with C++, Third Edition, Tony Gaddis
5.8Deciding WhichLoop to Use
The while loop
A pre-test loop.
Use when you do not want the loop to iterate if thecondition is false from the beginning.
Ideal if you want to use a sentinel.
The do-while loop
A post-test loop.
Use if you always want the loop to iterate at least once.
The for loop
A pre-test loop.
Automatically executes an update expression at the endof each iteration.
Ideal for situations where a counter variable is needed.
Used when the exact number of required iterations isknown.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
5.9Nested Loops
loop that is inside another loop iscalled a nested loop.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
for (int count1 = 1; count1 <= numStudents; count1++)
{
total = 0;      // Initialize accumulator
for (int count2 = 1; count2 <= numTests; count2++)
{
int score;
cout << "Enter score " << count2 << " for ";
cout << "student " << count1 << ": ";
cin >> score;
total += score;    // accumulate running total
}
average = total / numTests;
cout << "The average score for student " << count1;
cout << " is " << average << ".\n\n";
}
}
5-13 Program Continued
Resource: Starting Out with C++, Third Edition, Tony Gaddis
5-13 Program Output withExample Input
This program averages test scores.
For how many students do you have scores? 2 [Enter]
How many test scores does each student have?
3 [Enter]
Enter score 1 for student 1: 84 [Enter]
Enter score 2 for student 1: 79 [Enter]
Enter score 3 for student 1: 97 [Enter]
The average for student 1 is 86. 
Enter score 1 for student 2: 92 [Enter]
Enter score 2 for student 2: 88 [Enter]
Enter score 3 for student 2: 94 [Enter]
The average for student 2 is 91.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
5.10 Breaking Out of a Loop
The break statement causes a loop toterminate early.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
for (int count = 0; count <= 10; count++)
{
cout << value << " raised to the power of ";
cout << count << " is " << pow(value, count);
cout << "\nEnter Q to quit or any other key ";
cout << "to continue. ";
cin >> choice;
if (choice == 'Q' || choice == 'q')
break;
}
}
5-14 Program Continued
Resource: Starting Out with C++, Third Edition, Tony Gaddis
5-14 Program Output
Enter a number: 2 [Enter]
This program will raise 2 to the powers of 0
through 10.
2 raised to the power of 0 is 1
Enter Q to quit or any other key to
continue. C [Enter]
2 raised to the power of 1 is 2
Enter Q to quit or any other key to continue.
C [Enter]
2 raised to the power of 2 is 4
Enter Q to quit or any other key to continue.
Q [Enter]
Resource: Starting Out with C++, Third Edition, Tony Gaddis
5.11 Using break in a nestedloop
The break statement below breaks out ofthe inner loop but NOT the outer loop.
for(int row = 0; row < 5; row++)
  {  //begin outer loop
      for(star = 0; star  <  20; star++)
         {  //begin inner loop
               …………// some statements
                 break;
               …………// some more statements
          } //end inner loop
   } //end outer loop
Resource: Starting Out with C++, Third Edition, Tony Gaddis
5.11 The continue Statement
The continue statement causes aloop to stop its current iteration andbegin the next one.
Resource: Starting Out with C++, Third Edition, Tony Gaddis
do
{
if ((videoCount % 3) == 0)
{
cout << "Video #" << videoCount << " is free!\n";
continue;
}
cout << "Is video #" << videoCount;
cout << " a current release? (Y/N)";
cin >> current;
if (current == 'Y' || current == 'y')
total += 3.50;
else
total += 2.50;
} while (videoCount++ < numVideos);
cout.precision(2);
cout.setf(ios::fixed | ios::showpoint);
cout << "The total is $" << total;
}
5-15 Program Continued