Sei sulla pagina 1di 13

Program 5-1

The Increment and Decrement Operators

// This program demonstrates the increment and decrement


// operators.

++ and -- are operators that add and subtract


one from their operands.
num = num + 1;
num += 1;
num++;

#include <iostream.h>
void main(void)
{
int bigVal = 10, smallVal = 1;
cout << "bigVal is " << bigVal
<< " and smallVal is " << smallVal << endl;
smallVal++;
bigVal--;
Program continues

Starting Out with C++, 3rd Edition

Starting Out with C++, 3rd Edition

Program Output

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;

bigVal is 10 and smallVal is 1


bigVal is 9 and smallVal is 2
bigVal is 8 and smallVal is 3

Starting Out with C++, 3rd Edition

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>

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

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;
}

Starting Out with C++, 3rd Edition

Starting Out with C++, 3rd Edition

Using ++ and -- in Mathematical


Expressions

Using ++ and -- in Relational


Expressions

a = 2;
b = 5;
c = a * b++;
cout << a <<

x = 10;
if ( x++ > 10)
cout << x is greater than 10.\n;

<< b <<

<< c;

Two operations are happening:


the value in x is tested to determine if it is
greater than 10
then x is incremented

Results: 2 6 10

Starting Out with C++, 3rd Edition

Starting Out with C++, 3rd Edition

Program 5-3

5.2 Introduction to Loops - The while


Loop

// This program demonstrates a simple while loop.


#include <iostream.h>

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

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;
}

while (expression)
statement;
9

10

Starting Out with C++, 3rd Edition

Starting Out with C++, 3rd Edition

Program Output with Example Input

Terminating a Loop

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]

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);
11

Starting Out with C++, 3rd Edition

12

Starting Out with C++, 3rd Edition

Programming Style and the while Loop

5.3 Counters

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

A counter is a variable that is incremented


or decremented each time a loop iterates.

13

14

Starting Out with C++, 3rd Edition

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;

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

// Initialize counter

cout << "number


number Squared\n";
cout << "-------------------------\n";
while (num <= 10)
{
cout << num << "\t\t" << (num * num) << endl;
num++;
// Increment counter
}
}

15

Starting Out with C++, 3rd Edition

16

Starting Out with C++, 3rd Edition

Program 5-5
// This program displays the numbers 1 through 10
and
// their squares.
#include <iostream.h>

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

void main(void)
{
int num = 0;
cout << "number
number Squared\n";
cout << "-------------------------\n";
while (num++ < 10)
cout << num << "\t\t" << (num * num) <<
endl;
}
17

18

Starting Out with C++, 3rd Edition

Starting Out with C++, 3rd Edition

Program 5-6
5.4 Letting the User Control the Loop

// This program averages a set of test scores for multiple


// students. It lets the user decide how many.
#include <iostream.h>

We can let the user indicate the number of


times a loop should repeat.

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);

19

Starting Out with C++, 3rd Edition

Program continues

20

Starting Out with C++, 3rd Edition

Program continued from previous slide.

Program Output with Example Input

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";
}

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.

21

22

Starting Out with C++, 3rd Edition

Starting Out with C++, 3rd Edition

Program 5-7
5.5 Keeping a Running Total

// This program takes daily sales figures over a period of


// time and calculates their total.
#include <iostream.h>

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.

void main(void)
{
int days, count = 0;
float total = 0.0;
cout << "For how many days do you have sales figures? ";
cin >> days;

23

Starting Out with C++, 3rd Edition

Program continues

24

Starting Out with C++, 3rd Edition

Program Output with Example Input

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;

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

25

26

Starting Out with C++, 3rd Edition

Starting Out with C++, 3rd Edition

Program 5-8

5.6 Sentinels

// 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.

A sentinel is a special value that marks the


end of a list of values.

#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";

27

Starting Out with C++, 3rd Edition

Program continues

28

Starting Out with C++, 3rd Edition

Program continued from previous slide.

Program Output with Example Input


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;

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

29

30

Starting Out with C++, 3rd Edition

Starting Out with C++, 3rd Edition

Program 5-9

5.7 The do-while Loop and for


Loops

//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');
}

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);
31

Starting Out with C++, 3rd Edition

32

Starting Out with C++, 3rd Edition

Program Output with Example Input

The for Loop

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]

Ideal for situations that require a counter


because it has built-in expressions that
initialize and update variables.
for (initialization; test; update)
statement;

33

34

Starting Out with C++, 3rd Edition

Starting Out with C++, 3rd Edition

Program 5-11
// This program displays the numbers 1 through 10 and
// their squares.
#include <iostream.h>

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

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;
}

35

Starting Out with C++, 3rd Edition

36

Starting Out with C++, 3rd Edition

Omitting the for Loops Expressions

Using initialization and update lists

int num = 1;
for ( ; num <= 10; num++)
cout << num << \t\t << (num * num) << endl;

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.

37

38

Starting Out with C++, 3rd Edition

Starting Out with C++, 3rd Edition

Program 5-12
// This program takes daily sales figures for one week
// and calculates their total.

Program continued from previous slide.

cin >> sales;


total += sales;

#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

39

Starting Out with C++, 3rd Edition

}
cout.precision(2);
cout.setf(ios::fixed | ios::showpoint);
cout << "The total sales are $" << total << endl;
}

40

Starting Out with C++, 3rd Edition

10

5.8 Other forms of the update


expression

Program Output with Example Input

Incrementing the counter by something besides 1:


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

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!
41

Starting Out with C++, 3rd Edition

5.8 Focus on Software Engineering:


Deciding Which Loop to Use

42

Starting Out with C++, 3rd Edition

5.9 Focus on Software Engineering:


Nested Loops

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.
43

Starting Out with C++, 3rd Edition

A loop that is inside another loop is called a


nested loop.

44

Starting Out with C++, 3rd Edition

11

Program continued from previous slide.

Program 5-13

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";
}

// 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

45

46

Starting Out with C++, 3rd Edition

Starting Out with C++, 3rd Edition

5.10 Breaking Out of a Loop

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.

The break statement causes a loop to


terminate early.

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.
47

Starting Out with C++, 3rd Edition

48

Starting Out with C++, 3rd Edition

12

Program continued from previous slide.

Program 5-14
// This program raises the user's number to the powers
// of 0 through 10.
#include <iostream.h>
#include <math.h>

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;
}

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

49

Starting Out with C++, 3rd Edition

50

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]

51

Starting Out with C++, 3rd Edition

13

Potrebbero piacerti anche