CS102 Introduction to Computer Programming

Download Report

Transcript CS102 Introduction to Computer Programming

CS102
Introduction to Computer
Programming
Chapter 5 Looping
Chapter 5 Topics
• The Increment and
Decrement Operators
• Introduction to Loops
• The while Loop
• Counters
• Letting the User Control a
Loop
• Keeping a Running Total
•
•
•
•
•
•
•
•
Sentinels
The do-while Loop
The for Loop
Deciding Which Loop to
Use
Nested Loops
Breaking Out of a Loop
The continue Statement
Using Loops for Input
Validation
Increment and Decrement Operators
• Increment means increase by one
(Num = Num + 1) = = (Num +=1) = = (Num++)
• Decrement means decrease by one
(Num = Num - 1) = = (Num -=1) = = (Num--)
• ++ and-- are unary operators
Prefix mode
Postfix mode
increment/decrement is done first
increment/decrement is done last
• Operand must be an lvalue
Concept - ++ and -- are operators that add and subtract one
from their operands.
Program 5-1
// This program demonstrates the
increment and decrement operators.
#include <iostream>
using namespace std;
int main()
{
int BigVal = 10, SmallVal = 1;
cout << "BigVal is " << BigVal
<< " and SmallVal is " << SmallVal
<< endl;
SmallVal++;
BigVal--;
cout << "BigVal is " << BigVal
<< " and SmallVal is " <<
SmallVal << endl;
++SmallVal;
--BigVal;
cout << "BigVal is " << BigVal
<< " and SmallVal is " <<
SmallVal << endl;
return 0;
}
Program Output
BigVal is 10 and SmallVal is 1
BigVal is 9 and SmallVal is 2
BigVal is 8 and SmallVal is 3
Program 5-2
#include <iostream>
using namespace std;
int main(){
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;
return 0;
}
Note the difference between
Postfix andPre fix
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
Sample ++ -- operations
A. x = 2;
y = x++;
cout << x <<“,”<< y;
B. x = 2;
y = ++ x;
cout << x <<“,”<< y;
C. x = 2;
y = 4;
cout << x++ <<“,”;
cout << --y;
D. x = 2;
y = 2 * x++;
cout << x <<“,”<< y;
3, 2
3 ,3
2 ,3
3 ,4
E. x = 99;
if(x++ < 100)
cout <<"it is true";
else
cout <<"it is false";
F. x = 1;
if(-- x)
cout <<"it is true";
else
cout <<"it is false";
Loops
• A loop is a control structure which can
cause a statement or group of statements to
repeat
while
pre-test loop (may never execute)
do-while post-test loop (always execute once)
for
pre-test loop (may never execute)
Concept - A loop is a part of a program that can repeat
The while Loop
• The expression is tested for true or false
– if true, the statements are executed and the test
is made again
– if false, the loop is exited
while (expression)
statement;
while (number != 99)
cin >>number;
statement body
or
while (number != 99)
{
cin >>number;
cout << number;
}
while statement flow chart
while
(expression)
No
Yes
Statement
body
while Is a Pre-test Loop
• A pre-test loop executes zero or more times
– make sure you have a mechanism for
terminating the loop.
int x = 0;
while (x>10)
{
cout <<"hello";
}
Executes zero times
int x = 0;
while (x<10)
{
cout <<"hello";
}
This is an infinite loop
Concept - A pre-test loop evaluates its test-expression before
each iteration
Program 5-3
// This program demonstrates a simple while
loop.
#include <iostream>
using namespace std;
int main()
{
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;
return 0;
}
Program Output
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]
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);
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
Counters
• A counter controls the number of iterations that a
loop is executed
– Make sure the counter is properly initialized
– Be careful where the counter increments or decrements.
int num = 0;
while (num++ <10)
{
cout <<num;
}
What will the output look like
12345678910
Concept - a Counter is a variable that regularly increments or
decrements each time a loop iterates
Program 5-4
// This program displays the numbers 1 through 10 The increment in this while loop is in
and
the statement body
// their squares.
#include <iostream>
using namespace std;
Program Output
int main()
Number
Number Squared
{
------------------------int Num = 1;
1
1
2
4
cout << "Number Number Squared\n";
3
9
cout << "-------------------------\n";
4
16
while (Num <= 10)
5
25
{
6
36
49
cout << Num << "\t\t" << (Num * Num) 7
8
64
<< endl;
9
81
Num++;
10
100
}
return 0;
}
Program 5-5
// 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;
return 0;
}
The increment in this while loop is in
the conditional expression
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
Letting the User Control a Loop
• Be careful !!
– Range check all inputs
• Be sure that data conforms to the specification
– Reasonableness check all counters
• Check for abnormally large counters and loop
controls
– Give the user and your program a way out
• provide a mechanism for terminating the loop if an
error is encountered
Concept - Loops can be designed to repeat until the user enters
a particular value.
Program 5-6
/* This program averages a set of test scores
for multiple students. It lets the user decide
how many. */
#include <iostream>
using namespace std;
int main()
{
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 << fixed << precision(2);
If the user enters too large a number
there is no way to change it
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";
}
return 0;
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.
Keeping a Running Total
• Define a variable outside the while loop to
accumulate the running total
• Initialize the variable, usually to zero
• Allow the while loop to add to the running total
each iteration.
• Be careful with how you use the running total
when you exit the loop
– divide by zero
– over flows and underflows
Concept - A running total is a sum of numbers that accumulates
with each iteration.
Program 5-7
/* This program takes daily sales figures over a
cout << precision(2) << fixed <<
period of time and calculates their total. */
showpoint;
#include <iostream>
cout << "The total sales are $" <<
using namespace std;
Total << endl;
int main()
reuturn 0;
{
}
int Days, Count = 0;
float Total = 0.0;
cout << "For how many days do
you have sales figures? ";
Program Output
cin >> Days;
For how many days do you have sales figures?
while (Count++ < Days)
{
5 [Enter]
float Sales;
Enter the sales for day 1: 489.32 [Enter]
cout << "Enter the sales for day " ;
Enter the sales for day 2: 421.65 [Enter]
cout << Count << ": ";
cin >> Sales;
Enter the sales for day 3: 497.89 [Enter]
Total += Sales;
Enter the sales for day 4: 532.37 [Enter]
}
Enter the sales for day 5: 506.92 [Enter]
The total sales are $2448.15
Sentinels
• Provides a mechanism for terminating a loop
after an unspecified number of iterations
• A sentinel should be a value that would not
normally be part of the input list
– ie, a negative value for test scores
– must be the same data type
Concept - A sentinel is a special value that marks the end of a
list of values.
Sample Program
• This program calculates the average score for each
student
• It incorporates:
– user controlled loops
• user inputs the number of students
– counters
• counts the number of scores entered
– sentinels
• checks for no more scores
Program 5-8
while (Points != -1)
{
Count++;
cout << "Enter the points
for game " ;
cout << Count << ": ";
cin >> Points;
if (Points != -1)
Total += Points;
}
cout << "The total points are "
<< Total << endl;
}
return 0;
/* 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>
using namespace std;
int main()
{
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 finished.\n";
}
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
The do-while Loop
• An upside down while loop
– must be terminated with a semicolon after the
closing parenthesis of the test-expression
• The statement block executes at least once
– The expression is tested at the end of each
iteration
• Perfect for controlling menu selections
do while Statement Flow Chart
Statement
body
while
(expression)
No
Yes
Program 5-9
/* This program demonstrates the use of a dowhile loop*/
#include <iostream>
using namespace std;
int main()
{
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');
return 0;
}
Program Output
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]
Program 5-10
/* This program displays all of the
numbers in a file.*/
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int numbers;
ifstream inputFile;
else
{
inputFile >> number;
while (!inputFile.eof() )
{
cout << number << endl;
inputFile >> number;
}
inputFile.close()
}
inputFile.open(“numbers.txt”);
return 0;
if (!inputFile)
cout << “Error opening file.\n”; }
Program 5-12
/* 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>
using namespace std;
int main()
{
int Choice, Months;
float Charges;
cout.setf(ios::fixed | ios::showpoint);
cout.precision(2);
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
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;
case 4: cout << "Thanks for
using this ";
cout << "program.\n";
break;
default: cout << "The valid
choices are 1-4. ";
cout << "Try again.\n";
} #end of switch
} while (Choice != 4);
return 0;
}
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.
The for Loop
• for (initialization; test; update)
{
Place as many statements here as needed;
}
initialization
Yes
test
No
Statements
update
Program 5-13
/* This program displays the numbers 1
through 10 and their squares.*/
#include <iostream>
using namespace std;
int main()
{
int Num;
cout << "Number Number Squared\n";
cout << "-------------------------\n";
for (Num = 1; Num <= 10; Num++)
{
cout << Num << '\t\t' ;
cout<< (Num * Num) << endl;
}
return 0;
}
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
Parts of the for loop
• Initialization (an assignment statement)
– sets up the counter with a starting value
– only done once
• Test (a relational expression)
– Tests the counter against a specified condition
• Update (an assignment statement)
– changes the counter by the specified amount
• Statements (any valid C++ Statement)
– statements executed only if the test results in a
true condition.
Examples
for (num=1; num< 10; num++)
{
if (num== 7)
continue;
cout <<"\nThe count is "
<<num;
}
Prints the numbers 1 thru 9 but
skips 7
cin >> age;
for (num=age; num>0; num--)
cout <<"Happy Birthday";
Prints Happy birthday as many
times as you are years old
cin >> savings;
for(;savings<1e7;)
{cout <<"I still need to
work";
cin >> deposit;
savings += deposit;}
Adds deposits to your initial
savings account until you have
at least a million dollars
Program 5-14
// This program takes daily sales figures for one
week and calculates their total.*/
cout << precision(2) << fixed
#include <iostream>
<< showpoint;
using namespace std;
cout << "The total sales
int main()
Defines and initializes
are $" << Total << endl;
{
a running total
` return 0;
const int Days = 7;
int Count;
}
float Total;
for (Count = 1, Total = 0.0; Count <= Days;
Program Output
Count++)
Enter the sales for day 1: 489.32 [Enter]
{
Enter the sales for day 2: 421.65 [Enter]
float Sales;
Enter the sales for day 3: 497.89 [Enter]
cout << "Enter the sales for day ";
Enter the sales for day 4: 532.37 [Enter]
cout << Count << ": ";
Enter the sales for day 5: 506.92 [Enter]
cin >> Sales;
Total += Sales;
Enter the sales for day 6: 489.01 [Enter]
}
Enter the sales for day 7: 476.55 [Enter]
The total sales are $3413.71
Omitting the for Loop’s
Expressions
for (int num =1; Num <= 10; Num++)
cout << Num << “\t\t” << (Num * Num) << endl;
Or
int Num = 1;
for ( ;; )
{
if (Num <= 10)
cout << Num << “\t\t” << (Num * Num) << endl;
else
break;
Num++;
}
Complex for Loops
• Initializing multiple variables;
– Any number of variables can be initialized
– assignment statements are separated by a ,
• Logical and relational test conditions
– as long as the expression results in true or false
• Updating multiple variables
– Same as for initializing variables
• Variables can be declared within the for
loop
– limits their scope to the for loop
Deciding Which Loop to Use
• while loops are useful when you might not
want the loop to execute at all
– while you are home answer the phone
• do-while loops are useful when the loop
must execute at least one time
– let the phone ring until it is answered
• for loops are useful when you know the
number of times the loop must execute
– let the phone ring 5 times then hang up
Nested Loops
• An inner loop goes through all of its
iterations for each iteration of an outer loop
• Inner loops complete their iterations faster
than outer loops
• To get the total number of iterations of a
nested loop multiply the number of
iterations of all the loops
Program
5-15
// This program averages test scores. It for (int student = 1; student <= NumStudents;
student ++)
asks the user for the number of
{
students and the number of test
scores per student.*/
Total = 0;
Outer for loop
for (int test = 1; test <= NumTests;
#include <iostream>
test ++)
using namespace std;
{
int main()
int Score;
{
cout << "Enter score " << test
int NumStudents, NumTests, Total;
<< " for ";
Inner
for
loop
float Average;
cout << "student " << student
<< ": ";
cin >> Score;
Total += Score;
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;
}
Average = Total / NumTests;
cout << "The average score for student "
<< student;
cout << " is " << Average << ".\n\n";
}
return 0;
}
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.
Breaking Out of a Loop
• Used to prematurely terminate the execution
of a while, do-while or for loop
– Same statement used in the switch statement
• When the break statement is encountered
the program jumps the the next statemetn
following the loop.
• Gives the user an opportunity to terminate
an infinite loop
Concept - The break statement causes a loop to terminate early
Program 5-16
// This program raises the user's number
to the powers of 0 through 10.*/
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int Value;
Allows the loop to be
char Choice;
prematurely terminated
cout << "Enter a number: ";
cin >> Value;
cout << "This program will raise " <<
Value;
cout << " to the powers of 0 through 10.\n";
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;
}
return 0;
}
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]
The continue Statement
• Any statements that follow the continue are
ignored
– Execution goes to test portion of the while and
do-while and to the update part of the for loop
• Can be used to
– handle special cases
– exclude invalid input from affecting the
execution of the loop
Concept - The continue statement causes a loop to stop its
current iteration and begin the next one.
Program 5-17
// This program calculates the charges for video
cout << " a current release? (Y/N)";
rentals. Every third video is free.*/
cin >> Current;
#include <iostream>
if (Current == 'Y' || Current == 'y')
#include <iomanip>
Total += 3.50;
using namespace std;
else
int main()
Total += 2.50;
{
} while (VideoCount++ < NumVideos);
int VideoCount = 1, NumVideos;
cout << precision(2) << fixed;
float Total = 0.0;
char Current;
cout << "The total is $" << Total;
cout << "How many videos are being rented? "; return 0;
cin >> NumVideos;
}
Program Output
do
How many Videos are being rented? 6 [Enter]
{
Is video #1 a current release? y [Enter]
if ((VideoCount % 3) == 0)
Is video #2 a current release? n [Enter]
{
Video #3 is free!
cout << "Video #" << VideoCount
<< " is free!\n";
Is video #4 a current release? n [Enter]
Skips this
continue;
Is video #5 a current release? y [Enter]
iteration
}
Video #6 is free!
cout << "Is video #" << VideoCount;
The total is $12.00
Program Output with Example Input
Program Output
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
Using Loops for Input Validation
• A loop can let the user re-enter data as many
times as necessary until the values are in
range.
– Particularly useful if the program must have
valid input in order to continue
– Be sure to let the user know what valid data is
Concept - A loop can be used to create input routines that repeat
until acceptable data is entered.
Program 5-18
/* This program calculates the number of
soccer teams that a youth league may
create from the number of available
players. Input validation I demonstrated
with do-while loops.*/
#include <iostream>
using namespace std;
int main()
{
int Players, Max, NumTeams, LeftOver;
do
{
cout << "What is the maximum
number of players per team? ";
cin >> Max;
if (Max < 9 || Max > 15)
{
cout << "You should have at
least 9 but no\n";
cout << "more than 15 per
team.\n";
}
} while (Max < 9 || Max > 15);
do
{
cout << "How many players are
available? ";
cin >> Players;
if (Players < 0)
cout << "Please enter a positive
number.\n";
} while (Players < 0);
NumTeams = Players / Max;
LeftOver = Players % Max;
cout << "There will be " << NumTeams <<
" teams with\n";
cout << LeftOver << " players left
over.\n";
return 0;
}