Looping
1
Starting Out with C++, 3rd Edition
5.1 The Increment and Decrement
Operators
2
Starting Out with C++, 3rd Edition
Program 5-1
// This program demonstrates the increment and decrement
// operators.
#include <iostream.h>
void main(void)
{
int bigVal = 10, smallVal = 1;
Program continues…
3
Starting Out with C++, 3rd Edition
Program continued from previous slide.
4
Starting Out with C++, 3rd Edition
Program Output
5
Starting Out with C++, 3rd Edition
Program 5-2
//This program demonstrates the prefix and postfix modes of the
// increment and decrement operators.
#include <iostream.h>
void main(void)
{
int bigVal = 10, smallVal = 1;
cout << "bigVal starts as " << bigVal;
cout << " and smallVal starts as " << smallVal << endl;
cout << "bigVal--: " << bigVal-- << endl;
cout << "smallVal++: " << smallVal++ << endl;
cout << "Now bigVal is: " << bigVal << endl;
cout << "Now smallVal is: " << smallVal << endl;
cout << "--bigVal: " << --bigVal << endl;
cout << "++smallVal: " << ++smallVal << endl;
}
6
Starting Out with C++, 3rd Edition
Program Output
7
Starting Out with C++, 3rd Edition
Using ++ and -- in Mathematical
Expressions
a = 2;
b = 5;
c = a * b++;
cout << a << “ “ << b << “ “ << c;
Results: 2 6 10
8
Starting Out with C++, 3rd Edition
Using ++ and -- in Relational
Expressions
x = 10;
if ( x++ > 10)
cout << “x is greater than 10.\n”;
• Two operations are happening:
• the value in x is tested to determine if it is
greater than 10
• then x is incremented
9
Starting Out with C++, 3rd Edition
5.2 Introduction to Loops - The while
Loop
while (expression)
statement;
10
Starting Out with C++, 3rd Edition
Program 5-3
// This program demonstrates a simple while loop.
#include <iostream.h>
void main(void)
{
int number = 0;
cout << "This program will let you enter number
after\n";
cout << "number. Enter 99 when you want to quit the
";
cout << "program.\n";
while (number != 99)
cin >> number;
}
11
Starting Out with C++, 3rd Edition
Program Output with Example Input
This program will let you enter number after number. Enter
99 when you want to quit the program.
1 [Enter]
2 [Enter]
30 [Enter]
75 [Enter]
99 [Enter]
12
Starting Out with C++, 3rd Edition
Terminating a Loop
13
Starting Out with C++, 3rd Edition
Programming Style and the while Loop
15
Starting Out with C++, 3rd Edition
Program 5-4
// This program displays the numbers 1 through 10 and
// their squares.
#include <iostream.h>
void main(void)
{
int num = 1; // Initialize counter
16
Starting Out with C++, 3rd Edition
Program Output
17
Starting Out with C++, 3rd Edition
Program 5-5
// This program displays the numbers 1 through 10
and
// their squares.
#include <iostream.h>
void main(void)
{
int num = 0;
cout << "number number Squared\n";
cout << "-------------------------\n";
while (num++ < 10)
cout << num << "\t\t" << (num * num) <<
endl;
}
18
Starting Out with C++, 3rd Edition
Program Output
19
Starting Out with C++, 3rd Edition
5.4 Letting the User Control the Loop
20
Starting Out with C++, 3rd Edition
Program 5-6
// This program averages a set of test scores for multiple
// students. It lets the user decide how many.
#include <iostream.h>
void main(void)
{
int numStudents, count = 0;
Program continues…
21
Starting Out with C++, 3rd Edition
Program continued from previous slide.
22
Starting Out with C++, 3rd Edition
Program Output with Example Input
This program will give you the average of three test scores 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.
23
Starting Out with C++, 3rd Edition
5.5 Keeping a Running Total
24
Starting Out with C++, 3rd Edition
Program 5-7
// This program takes daily sales figures over a period of
// time and calculates their total.
#include <iostream.h>
void main(void)
{
int days, count = 0;
float total = 0.0;
cout << "For how many days do you have sales figures? ";
cin >> days;
Program continues…
25
Starting Out with C++, 3rd Edition
Program continues
26
Starting Out with C++, 3rd Edition
Program Output with Example Input
27
Starting Out with C++, 3rd Edition
5.6 Sentinels
28
Starting Out with C++, 3rd Edition
Program 5-8
// This program calculates the total number of points a
// soccer team has earned over a series of games. The user
// enters a series of point values, then -1 when finished.
#include <iostream.h>
void main(void)
{
int count = 0, points = 0, total = 0;
cout << "Enter the number of points your team has earned\n";
cout << "so far in the season, then enter -1 when\n";
cout << "finished.\n";
Program continues…
29
Starting Out with C++, 3rd Edition
Program continued from previous slide.
30
Starting Out with C++, 3rd Edition
Program Output with Example Input
Enter the number of points your team has earned 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
31
Starting Out with C++, 3rd Edition
5.7 The do-while Loop and for
Loops
32
Starting Out with C++, 3rd Edition
Program 5-9
//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');
}
33
Starting Out with C++, 3rd Edition
Program Output with Example Input
34
Starting Out with C++, 3rd Edition
Program 5-10
// This program displays a menu and asks the user to make a
// selection. A switch statement determines which item the
// user has chosen. A do-while loop repeats the program until
// the user selects item 4 from the menu.
#include <iostream.h>
void main(void)
{
int choice, months;
float charges;
cout.setf(ios::fixed | ios::showpoint);
cout.precision(2);
Program continues…
35
Starting Out with C++, 3rd Edition
Program continued from previous slide.
do
{
cout << "\n\t\tHealth Club Membership Menu\n\n";
cout << "1. Standard Adult Membership\n";
cout << "2. Child Membership\n";
cout << "3. Senior Citizen Membership\n";
cout << "4. Quit the Program\n\n";
cout << "Enter your choice: ";
cin >> choice;
if (choice != 4)
{
cout << "For how many months? ";
cin >> months;
}
Program continues…
36
Starting Out with C++, 3rd Edition
Program continued from previous slide.
switch (choice)
{
case 1: charges = months * 40.00;
cout << "The total charges are $";
cout << charges << endl;
break;
case 2: charges = months * 20.00;
cout << "The total charges are $";
cout << charges << endl;
break;
case 3: charges = months * 30.00;
cout << "The total charges are $";
cout << charges << endl;
break;
Program continues…
37
Starting Out with C++, 3rd Edition
Program continued from previous slide.
Program continues…
38
Starting Out with C++, 3rd Edition
Program Output with Example Input
40
Starting Out with C++, 3rd Edition
Program 5-11
// This program displays the numbers 1 through 10 and
// their squares.
#include <iostream.h>
void main(void)
{
int num;
41
Starting Out with C++, 3rd Edition
Program Output
42
Starting Out with C++, 3rd Edition
Omitting the for Loop’s Expressions
int num = 1;
for ( ; num <= 10; num++)
cout << num << “\t\t” << (num * num) << endl;
43
Starting Out with C++, 3rd Edition
Using initialization and update lists
44
Starting Out with C++, 3rd Edition
Program 5-12
// This program takes daily sales figures for one week
// and calculates their total.
#include <iostream.h>
void main(void)
{
const int days = 7;
int count;
float total;
for (count = 1, total = 0.0; count <= days; count++)
{
float sales;
cout << "Enter the sales for day " << count << ": ";
Program continues…
45
Starting Out with C++, 3rd Edition
Program continued from previous slide.
46
Starting Out with C++, 3rd Edition
Program Output with Example Input
47
Starting Out with C++, 3rd Edition
5.8 Other forms of the update
expression
• Incrementing the counter by something besides 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
48
Starting Out with C++, 3rd Edition
5.8 Focus on Software Engineering:
Deciding Which Loop to Use
• The while Loop
• A pre-test loop.
• Use when you do not want the loop to iterate if the condition 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 end of each iteration.
• Ideal for situations where a counter variable is needed.
• Used when the exact number of required iterations is known.
49
Starting Out with C++, 3rd Edition
5.9 Focus on Software Engineering:
Nested Loops
50
Starting Out with C++, 3rd Edition
Program 5-13
// This program averages test scores. It asks the user for the
// number of students and the number of test scores per student.
#include <iostream.h>
void main(void)
{
int numStudents, numTests, total;
float average;
Program continues…
51
Starting Out with C++, 3rd Edition
Program continued from previous slide.
52
Starting Out with C++, 3rd Edition
Program Output with Example Input
53
Starting Out with C++, 3rd Edition
5.10 Breaking Out of a Loop
54
Starting Out with C++, 3rd Edition
Program 5-14
// This program raises the user's number to the powers
// of 0 through 10.
#include <iostream.h>
#include <math.h>
void main(void)
{
int value;
char choice;
Program continues…
55
Starting Out with C++, 3rd Edition
Program continued from previous slide.
56
Starting Out with C++, 3rd Edition
Program Output
57
Starting Out with C++, 3rd Edition
5.11 Using break in a nested loop
• The break statement below breaks out of the 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
58
Starting Out with C++, 3rd Edition
5.11 The continue Statement
59
Starting Out with C++, 3rd Edition
Program 5-15
// This program calculates the charges for video
rentals.
// Every third video is free.
#include <iostream.h>
#include <iomanip.h>
void main(void)
{
int videoCount = 1, numVideos;
float total = 0.0;
char current;
Program continues…
60
Starting Out with C++, 3rd Edition
Program continued from previous slide.
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);
Program continues…
61
Starting Out with C++, 3rd Edition
Program continued from previous slide.
cout.precision(2);
cout.setf(ios::fixed | ios::showpoint);
cout << "The total is $" << total;
}
62
Starting Out with C++, 3rd Edition
Program Output with Example Input
63
Starting Out with C++, 3rd Edition
5.12 Using Loops for Input Validation
64
Starting Out with C++, 3rd Edition
Program 5-16
// This program calculates the number of soccer teams
// that a youth league may create from the number of
// available players. Input validation is demonstrated
// with do-while loops.
#include <iostream.h>
void main(void)
{
int players, teamPlayers, numTeams, leftOver;
Program continues…
65
Starting Out with C++, 3rd Edition
Program continued from previous slide.
66
Starting Out with C++, 3rd Edition
Program Output with Example Input
67
Starting Out with C++, 3rd Edition