loops in c++_2015_2

Download Report

Transcript loops in c++_2015_2

Chapter 5.
Looping
1
Starting Out with C++, 3rd Edition
2
Starting Out with C++, 3rd Edition
3
Starting Out with C++, 3rd Edition
My first C++ program
•
•
•
•
•
•
•
#include <iostream>
using namespace std;
int main()
{
cout << "My first C++ program." << endl;
return 0;
}
4
Starting Out with C++, 3rd Edition
5
Starting Out with C++, 3rd Edition
•
•
•
•
•
•
•
•
•
•
•
•
#include <iostream>
using namespace std;
int main()
{
int num;
num = 6;
cout << "My first C++ program." << endl;
cout << "The sum of 2 and 3 = " << 5 << endl;
cout << "7 + 8 = " << 7 + 8 << endl;
cout << "Num = " << num << endl;
return 0;
}
6
Starting Out with C++, 3rd Edition
• Special Symbols The smallest individual unit of a program
written in any language is called a token.
• C++’s tokens are divided into special symbols, word
symbols, and identifiers.
• 32 | Chapter 2: Basic Elements of C++Following are some
of the special symbols:
• +-*/
• .;?,
• <= != == >=
7
Starting Out with C++, 3rd Edition
Illegal variables identifiers
8
Starting Out with C++, 3rd Edition
Data type
• Data type: A set of values together with a
set of operations.
• C++ data types fall into the following three
categories and are illustrated in Figure 2-1:
• 1. Simple data type
• 2. Structured data type
• 3. Pointers
9
Starting Out with C++, 3rd Edition
• Integers in C++, as in mathematics, are numbers such as the
following:
-6728, -67, 0, 78, 36782, +763
char
• 'A', 'a', '0', '*', '+', '$', '&', ' '
10
Starting Out with C++, 3rd Edition
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Arithmetic Expression Result Description
2+57
13 + 89
102
34 – 20 14
45 – 90
-45
2*7
14
5/2
2 In the division 5 / 2, the quotient is 2 and the
remainder is 1. Therefore, 5 / 2 with the integral
operands evaluates to the quotient, which is 2.
14 / 7
2
34 % 5
4 In the division 34 / 5, the quotient is 6 and the
remainder is 4. Therefore, 34 % 5 evaluates to the
remainder, which is 4.
4%6
4
In the division 4 / 6, the quotient is 0 and the
remainder is 4. Therefore, 4 % 6 evaluates to the
remainder, which is 4.
11
Starting Out with C++, 3rd Edition
12
Starting Out with C++, 3rd Edition
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
// This program illustrates how data in the variables are // manipulated.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int num1, num2;
double sale;
char first;
string str;
num1 = 4;
cout << "num1 = " << num1 << endl;
num2 = 4 * 5 - 11;
cout << "num2 = " << num2 << endl;
sale = 0.02 * 1000;
cout << "sale = " << sale << endl;
first = 'D';
cout << "first = " << first << endl;
str = "It is a sunny day.";
cout << "str = " << str << endl;
return 0;
}
13
Starting Out with C++, 3rd Edition
•
// This program illustrates how input statements work.
•
•
•
•
•
•
•
•
•
•
•
•
•
#include <iostream>
using namespace std;
int main()
{
int feet;
int inches;
cout << "Enter two integers separated by spaces: ";
cin >> feet >> inches;
cout << endl;
cout << "Feet = " << feet << endl;
cout << "Inches = " << inches << endl;
return 0;
}
•
•
•
•
/*Sample Run: In this sample run, the user input is shaded.
Enter two integers separated by spaces: 23 7
Feet = 23
Inches = 7*/
14
Starting Out with C++, 3rd Edition
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
// This program illustrates how output statements work.
#include <iostream>
using namespace std;
int main()
{
int a, b;
a = 65; //Line 1
b = 78; //Line 2 Output | 69
cout << 29 / 4 << endl; //Line 3
cout << 3.0 / 2 << endl; //Line 4
cout << "Hello there.\n"; //Line 5
cout << 7 << endl; //Line 6
cout << 3 + 5 << endl; //Line 7
cout << "3 + 5"; //Line 8
cout << endl; //Line 9
cout << a << endl; //Line 10
cout << "a" << endl; //Line 11
cout << (a + 5) * 6 << endl; //Line 12
cout << 2 * b << endl; //Line 13
return 0;
}
15
Starting Out with C++, 3rd Edition
•
•
•
•
•
•
•
x = 5;
y = ++x; x=6 while y=6
x = 5;
y = x++;
x=6 y=5
a = 5;
b = 2 + (a++);
the value of (a) is 6 while the value of b is 7.
16
Starting Out with C++, 3rd Edition
17
Starting Out with C++, 3rd Edition
Relational Operators in C++
18
Starting Out with C++, 3rd Edition
expressions using these operators
evaluate to true or false
19
Starting Out with C++, 3rd Edition
20
Starting Out with C++, 3rd Edition
Logical (Boolean) Operators and Logical
Expressions
21
Starting Out with C++, 3rd Edition
22
Starting Out with C++, 3rd Edition
Two-Way Selection
•
•
•
•
if (expression)
statement1
else
Statement2
•
•
•
•
•
if (hours > 40.0) //Line 1
wages = 40.0 * rate +
1.5 * rate *(hours - 40.0); //Line 2
else //Line 3
wages = hours * rate;
23
Starting Out with C++, 3rd Edition
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
#include <iostream>
#include <iomanip>
using namespace std;
int main()
double wages, rate, hours;
cout << fixed << showpoint << setprecision(2); //Line 1
cout << "Line 2: Enter working hours and rate: "; //Line 2
cin >> hours >> rate; //Line 3
if (hours > 40.0) //Line 4
wages = 40.0 * rate +1.5 * rate * (hours - 40.0); //Line 5
else //Line 6
wages = hours * rate; //Line 7
cout << endl; //Line 8
cout << "Line 9: The wages are $" << wages
<< endl; //Line 9
return 0;
}
24
Starting Out with C++, 3rd Edition
Compound (Block of) Statements
•
•
•
•
•
•
•
•
{
statement_1
statement_2
.
.
.
statement_n
}
25
Starting Out with C++, 3rd Edition
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
if (age >= 18)
cout << "Eligible to vote." << endl;
else
cout << "Not eligible to vote." << endl;
you could include compound statements, similar to the following code:
if (age >= 18)
{
cout << "Eligible to vote." << endl;
cout << "No longer a minor." << endl;
}
else
{
cout << "Not eligible to vote." << endl;
cout << "Still a minor." << endl;
}
26
Starting Out with C++, 3rd Edition
•
•
•
•
•
•
•
•
•
•
if (balance > 50000.00) //Line 1
interestRate = 0.07; //Line 2
else //Line 3
if (balance >= 25000.00) //Line 4
interestRate = 0.05; //Line 5
else //Line 6
if (balance >= 1000.00) //Line 7
interestRate = 0.03; //Line 8
else //Line 9
interestRate = 0.00;
27
Starting Out with C++, 3rd Edition
•
•
•
•
•
•
•
•
•
•
if (score >= 90)
cout << "The grade is A." << endl;
else if (score >= 80)
cout << "The grade is B." << endl;
else if (score >= 70)
cout << "The grade is C." << endl;
else if (score >= 60)
cout << "The grade is D." << endl;
else
cout << "The grade is F." << endl;
28
Starting Out with C++, 3rd Edition
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
#include<iostream> // Required for cout
using namespace std;
int main()
{ int month;
cin>>month;
if ( month == 1) //Line 1
cout << "January" << endl; //Line 2
else if (month == 2) //Line 3
cout << "February" << endl; //Line 4
else if (month == 3) //Line 5
cout << "March" << endl; //Line 6
else if (month == 4) //Line 7
cout << "April" << endl; //Line 8
else if (month == 5) //Line 9
cout << "May" << endl; //Line 10
else if (month == 6) //Line 11
cout << "June" << endl; //Line 12
if (month == 1)
cout << "January" << endl;
if (month == 2)
cout << "February" << endl;
if (month == 3)
cout << "March" << endl;
if (month == 4)
cout << "April" << endl;
if (month == 5)
cout << "May" << endl;
if (month == 6)
cout << "June" << endl;
return( 0);
}
29
Starting Out with C++, 3rd Edition
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
double x = 1.0;
double y = 3.0 / 7.0 + 2.0 / 7.0 + 2.0 / 7.0;
cout << fixed << showpoint << setprecision(17);
cout << "3.0 / 7.0 + 2.0 / 7.0 + 2.0 / 7.0 = "
<< 3.0 / 7.0 + 2.0 / 7.0 + 2.0 / 7.0 << endl;
cout << "x = " << x << endl;
cout << "y = " << y << endl;
if (x == y)
cout << "x and y are the same." << endl;
else
cout << "x and y are not the same." << endl;
if (fabs(x - y) < 0.000001)
cout << "x and y are the same within the tolerance "
<< "0.000001." << endl;
else
cout << " x and y are not the same within the “ << "tolerance 0.000001." << endl;
return 0; }
30
Starting Out with C++, 3rd Edition
31
Starting Out with C++, 3rd Edition
5.1 The Increment and Decrement
Operators
• ++ and -- are operators that add and subtract
one from their operands.
num = num + 1;
num += 1;
num++;
32
Starting Out with C++, 3rd Edition
/*-------------------------------------------------------------*/
/* Program chapter4_2
*/
/* This program prints a degree-to-radian table
*/
/* using a while loop structure.
*/
#include<iostream> //Required for cout
#include<iomanip> //Required for setw()
using namespace std;
const double PI = 3.141593;
int main()
{
// Declare and initialize objects.
int degrees(0);
double radians;
// Set formats.
cout.setf(ios::fixed);
cout.precision(6);
// Print radians and degrees in a loop.
cout << "Degrees to Radians \n";
while (degrees <= 360)
{
radians = degrees*PI/180;
cout << setw(6) << degrees << setw(10) << radians << endl;
degrees += 10; }
// Exit program.
return 0; }
/*-------------------------------------------------------------*/
Program continues…
33
Starting Out with C++, 3rd Edition
Program continued from previous slide.
cout << "bigVal is " << bigVal
<< " and smallVal is " << smallVal << endl;
++smallVal;
--bigVal;
cout << "bigVal is " << bigVal
<< " and smallVal is " << smallVal << endl;
}
34
Starting Out with C++, 3rd Edition
Program Output
bigVal is 10 and smallVal is 1
bigVal is 9 and smallVal is 2
bigVal is 8 and smallVal is 3
35
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;
}
36
Starting Out with C++, 3rd Edition
Program Output
bigVal starts as 10 and smallVal starts as 1
bigVal--: 10
smallVal++: 1
Now bigVal is: 9
Now smallVal is: 2
--bigVal: 8
++smallVal: 3
37
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
38
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
39
Starting Out with C++, 3rd Edition
5.2 Introduction to Loops - The while
Loop
• A loop is part of a program that repeats.
• A while loop is a “pre test” loop - the
expression is tested before the loop is
executed
while (expression)
statement;
40
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;
}
41
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]
42
Starting Out with C++, 3rd Edition
Terminating a Loop
A loop that does not have a way of stopping is called
an infinite loop
int test = 0;
while (test < 10)
cout << “Hello\n”;
A null statement is also an infinite loop, but it does
nothing forever:
while (test < 10);
43
Starting Out with C++, 3rd Edition
Programming Style and the while Loop
• If there is only one statement repeated by
the loop, it should appear on the line after
the while statement and be indented one
additional level
• If the loop repeats a block, the block should
begin on the line after the while statement
and each line inside the braces should be
indented
44
Starting Out with C++, 3rd Edition
5.3 Counters
• A counter is a variable that is incremented
or decremented each time a loop iterates.
45
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
cout << "number
number Squared\n";
cout << "-------------------------\n";
while (num <= 10)
{
cout << num << "\t\t" << (num * num) << endl;
num++;
// Increment counter
}
}
46
Starting Out with C++, 3rd Edition
Program Output
number
number Squared
------------------------1
1
2
4
3
9
4
16
5
25
6
36
7
49
8
64
9
81
10
100
47
Starting Out with C++, 3rd Edition
Program 5-5 While loop
// This program displays the numbers 1 through 10
and
// their squares.
#include <iostream>
using namespace std;
int main()
{ int
num = 0;
cout << "number
number Squared\n";
cout << "-------------------------\n";
while (num++ < 10)
cout << num << "\t\t" << (num * num) <<
endl;
}
48
Starting Out with C++, 3rd Edition
Program Output
number
number Squared
------------------------1
1
2
4
3
9
4
16
5
25
6
36
7
49
8
64
9
81
10
100
49
Starting Out with C++, 3rd Edition
5.4 Letting the User Control the Loop
• We can let the user indicate the number of
times a loop should repeat.
50
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;
cout << "This program will give you the average of
three\n";
cout << "test scores per student.\n";
cout << "How many students do you have test scores for? ";
cin >> numStudents;
cout << "Enter the scores for each of the students.\n";
cout.precision(2);
Program continues…
51
Starting Out with C++, 3rd Edition
Program continued from previous slide.
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";
}
}
52
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.
53
Starting Out with C++, 3rd Edition
5.5 Keeping a Running Total
• A running total is a sum of numbers that
accumulates with each iteration of a loop.
The variable used to keep the running total
is called an accumulator.
54
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…
55
Starting Out with C++, 3rd Edition
Program continues
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;
}
56
Starting Out with C++, 3rd Edition
Program Output with Example Input
For how many days do you have sales figures? 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
57
Starting Out with C++, 3rd Edition
5.6 Sentinels
• A sentinel is a special value that marks the
end of a list of values.
58
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…
59
Starting Out with C++, 3rd Edition
Program continued from previous slide.
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;
}
60
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
61
Starting Out with C++, 3rd Edition
5.7 The do-while Loop and for
Loops
• In addition to the while loop, C++ also
offers the do-while and for loops.
• A do-while loop is similar to a while loop,
but in post-test format:
do
statement;
while (expression);
62
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');
}
63
Starting Out with C++, 3rd Edition
Program Output with Example 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]
64
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…
65
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…
66
Starting Out with C++, 3rd Edition
Program continued from previous slide.
switch (choice)
{
case 1: charges
cout <<
cout <<
break;
case 2: charges
cout <<
cout <<
break;
case 3: charges
cout <<
cout <<
break;
Program continues…
= months * 40.00;
"The total charges are $";
charges << endl;
= months * 20.00;
"The total charges are $";
charges << endl;
= months * 30.00;
"The total charges are $";
charges << endl;
67
Starting Out with C++, 3rd Edition
Program continued from previous slide.
case 4:
cout << "Thanks for using this ";
cout << "program.\n";
break;
default: cout << "The valid choices are 1-4. ";
cout << "Try again.\n";
}
} while (choice != 4);
}
Program continues…
68
Starting Out with C++, 3rd Edition
Program Output with Example Input
Health Club Membership Menu
1. Standard Adult Membership
2. Child Membership
3. Senior Citizen Membership
4. Quit the Program
Enter your choice: 1 [Enter]
For how many months 12 [Enter]
The total charges are $480.00
Health Club Membership Menu
1. Standard Adult Membership
2. Child Membership
3. Senior Citizen Membership
4. Quit the Program
Enter your choice: 4 [Enter]
Thanks for using this program.
69
Starting Out with C++, 3rd Edition
The for Loop
• Ideal for situations that require a counter
because it has built-in expressions that
initialize and update variables.
for (initialization; test; update)
statement;
70
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;
cout << “Number
Number Squared\n";
cout << "-------------------------\n";
for (num = 1; num <= 10; num++)
cout << num << "\t\t" << (num * num) << endl;
}
71
Starting Out with C++, 3rd Edition
Program Output
Number
Number Squared
------------------------1
1
2
4
3
9
4
16
5
25
6
36
7
49
8
64
9
81
10
100
72
Starting Out with C++, 3rd Edition
Omitting the for Loop’s Expressions
#include <iostream>
using namespace std;
int main()
{ int
num = 0;
cout << "number
number Squared\n";
cout << "-------------------------\n";
for (num = 1; num <= 10; num++)
// while (num++ < 10)
cout << num << "\t\t" << (num * num) << endl;
}
73
Starting Out with C++, 3rd Edition
Using initialization and update lists
You may need to perform more than one
statement in the initialization part of a for
loop. In that case, just separate the
statements with commas.
74
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…
75
Starting Out with C++, 3rd Edition
Program continued from previous slide.
cin >> sales;
total += sales;
}
cout.precision(2);
cout.setf(ios::fixed | ios::showpoint);
cout << "The total sales are $" << total << endl;
}
76
Starting Out with C++, 3rd Edition
Program Output with Example Input
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]
Enter the sales for day 6: 489.01 [Enter]
Enter the sales for day 7: 476.55 [Enter]
The total sales are $3413.71
77
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
• 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 of your
own!
78
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.
79
Starting Out with C++, 3rd Edition
5.9 Focus on Software Engineering:
Nested Loops
• A loop that is inside another loop is called a
nested loop.
80
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;
cout << "This program averages test scores.\n";
cout << "For how many students do you have scores? ";
cin >> numStudents;
cout << "How many test scores does each student have? ";
cin >> numTests;
Program continues…
81
Starting Out with C++, 3rd Edition
Program continued from previous slide.
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";
}
}
82
Starting Out with C++, 3rd Edition
Program Output with Example 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.
83
Starting Out with C++, 3rd Edition
5.10 Breaking Out of a Loop
• The break statement causes a loop to
terminate early.
84
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;
cout << "Enter a number: ";
cin >> value;
cout << "This program will raise " << value;
cout << " to the powers of 0 through 10.\n";
Program continues…
85
Starting Out with C++, 3rd Edition
Program continued from previous slide.
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;
}
}
86
Starting Out with C++, 3rd Edition
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]
87
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
88
Starting Out with C++, 3rd Edition
5.11 The continue Statement
• The continue statement causes a loop to
stop its current iteration and begin the next
one.
89
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;
cout << "How many videos are being rented? ";
cin >> numVideos;
Program continues…
90
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…
91
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;
}
92
Starting Out with C++, 3rd Edition
Program Output with Example Input
How many Videos are being rented? 6 [Enter]
Is video #1 a current release? y [Enter]
Is video #2 a current release? n [Enter]
Video #3 is free!
Is video #4 a current release? n [Enter]
Is video #5 a current release? y [Enter]
Video #6 is free!
The total is $12.00
93
Starting Out with C++, 3rd Edition
5.12 Using Loops for Input Validation
• Loops can be used to create input routines
that repeat until acceptable data is entered.
94
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;
// Get the number of players per team.
cout << “How many players you wish per team?\n”;
cout << “(Enter a value in the range 9 - 15): ";
cin >> teamPlayers;
Program continues…
95
Starting Out with C++, 3rd Edition
Program continued from previous slide.
while (teamPlayers < 9 || teamPlayers > 15) // Validate input
{
cout << "You should have at least 9 but no\n";
cout << "more than 15 per team.\n";
cout << “How many players do you wish per team? “;
cin >> teamPlayers;
}
// Get the number of players available
cout << “How many players are available? “;
cin >> players;
while (players < 0) // Validate input
{
cout << "Please enter a positive number.\n";
cin >> players;
}
// Perform calculations
numTeams = players / teamPlayers;
leftOver = players % teamPlayers;
cout << "There will be " << numTeams << " teams with\n";
cout << leftOver << " players left over.\n";
}
96
Starting Out with C++, 3rd Edition
Program Output with Example Input
How many players you wish per team?
(Enter a value in the range 9 – 15): 4[Enter]
You should have at least 9 but no
more than 15 per team.
How many players you wish per team? 12[Enter]
How many players are available? -142 [Enter]
Please enter a positive number: 142[Enter]
There will be 11 teams with 10 players left over.
97
Starting Out with C++, 3rd Edition