Download Advanced Loops in C++: while, for, do-while, and Nested Loops and more Lecture notes C programming in PDF only on Docsity!
Week 7: Advanced Loops
Gaddis: 5.7-
CS 1428
Fall 2014
Jill Seaman
1
Loops in C++
(review)
2
• while
‣ if expression is true, statement is executed, repeat
• for
‣ equivalent to:
• do while
while (expression)!
statement
for (expr1; expr2; expr3)!
statement
do!
statement!
while (expression);
expr1;!
while (expr2) {!
statement!
expr3;!
statement is executed.
if expression is true, then repeat
statement may be a
compound statement
(a block: {statements})
Counting
(review)
3
! set a counter variable to 0
! increment it inside the loop (each iteration)
! after each iteration of the loop, it stores the # of
loop iterations so far
int number;! int count = 0;!
cout << “Enter a number between 1 and 10: “;! cin >> number;!
while (number < 1 || number > 10) {! count = count + 1;! cout << “Please enter a number between 1 and 10: “;! cin >> number;! }!
cout << count << “ invalid numbers entered “ << endl;!
// Do something with number here 4
! set an accumulator variable to 0
! add the next number to it inside the loop
! after each iteration of the loop, it stores the sum
of the numbers added so far (running total)
int days; //Counter for count-controlled loop! float total = 0.0; //Accumulator! float miles; //daily miles ridden!
cout << “How many days did you ride your bike? “;! cin >> days;!
for (int i = 1; i <= days; i++) {! cout << “Enter the miles for day “ << i << “: ”;! cin >> miles;! total = total + miles;! }!
cout << “Total miles ridden: “ << total << endl;
5.7 Keeping a running total
(summing)
total is 0 first time through
Keeping a running total
5
• Output:
• How would you calculate the average mileage?
How many days did you ride you bike? 3! Enter the miles for day 1: 1 4.2! Enter the miles for day 2: 2 5.4! Enter the miles for day 3: 1 2.2! Total miles ridden: 5 1.8! 6
! sentinel: special value in a list of values that
indicates the end of the data
! sentinel value must not be a valid value!
-99 for a test score, -1 for miles ridden
! User does not need to count how many values
will be entered
! Requires a “priming read” before the loop starts
‣ so the sentinel is NOT included in the sum
‣ the loop can be skipped (if first value is the sentinel)
5.8 Sentinel controlled loop
Sentinel example
7
• Example:
• Output:
float total = 0.0; //Accumulator! float miles; //daily miles ridden!
cout << “Enter the miles you rode on your bike each day, “;! cout << “then enter -1 when finished. “ << endl;!
cin >> miles; //priming read! while (miles != -1) {! total = total + miles; //skipped when miles==-1! cin >> miles; //get the next one! }!
cout << “Total miles ridden: “ << total << endl; Enter the miles you rode on your bike each day,! then enter -1 when finished.! 1 4.2! 2 5.4! 12.2! -1! Total miles ridden: 5 1.
5.9 Which Loop to use?
! Any loop can work for any given problem
! while loop:
‣ test at start of loop
‣ validating input, sentinel controlled loops, etc.
! for loop:
‣ initialize/test/update
‣ count-controlled loops
! do-while loop
‣ always do at least once
‣ good for repeating, simple menu processing 8
5.11 More File I/O
13
• Can test a file stream object as if it were a
boolean variable to check for various errors.
• After opening a file, if the open operation failed,
the value of file stream variable is false.
ifstream infile;!
infile.open("test.txt");!
if (!infile) {!
cout << "File open failure!";!
return 1;!
Reading data from a file
14
• Use fin>>x; in a loop
• Problem: when to stop the loop?
• First entry in file could be count of number of
items
‣ problems: maintenance, large files
• Could use sentinel value
‣ problem: may not be one, maintenance
• Want to automatically detect end of file
Using >> to detect end of file
15
! stream extraction operation (>>) returns true
when a value was successfully read, false
otherwise
! inputFile >> number:
‣ tries to read a value into number
‣ if it was successful, value is true
‣ if it failed (nothing left to input), value is false
(and the value in the variable does not change!)
int number;!
ifstream inputFile;!
inputFile.open(“numbers.txt”);!
bool foundValue = (inputFile >> number);
Using the result of >>
16
• Example:
• Can also use directly as relational expression:
int number;!
ifstream inputFile;!
inputFile.open(“numbers.txt”);!
bool foundValue = (inputFile >> number);!
if (foundValue)!
cout << “The data read in was: “ << number << endl;!
else!
cout << “Could not read data from file.” << endl;
if (inputFile >> number)! ...
Sum all the values in the file
17
• Code:
• numbers.txt: Output:
int number;!
ifstream inputFile;!
inputFile.open(“numbers.txt”);!
int total = 0;!
while (inputFile >> number) {!
total = total + number;!
cout << “The sum of the numbers in the file: “ << total!
<< endl;
84! The sum of the numbers in the file: 344 32! 99! 77! 52
5.12 Breaking and Continuing
18
• Sometimes we want to abort (exit) a loop before
it has completed.
• The break statement can be used to terminate
the loop from within:
• Don’t do this. It makes your code hard to read
and debug.
cout << “Guess a number between 1 and 10” << endl;!
int number;!
while (true) {!
cin >> number;!
if (number == 8)!
break;!
cout << “You got it.” << endl;
Stopping a single iteration
19
• Sometimes we want to abort an iteration (skip
to the end of loop body) before it is done.
• The continue statement can be used to
terminate the current iteration:
• Output:
• Don’t do this either. It makes your code hard to
read and debug.
for (int i=1; i <= 6; i++) {!
if (i == 4)!
continue;!
cout << i << “ “;!
Programming Assignment 4.
Practice
20
• Rewrite PA3, Prepare a Lab Report, so that it
uses a loop to enter the data for any number of
rats (ask the user to specify the number of rats
before the loop starts).
‣ Then rewrite it to take the input from a file (do not input the
number of rats, just loop until the end of the file).
• Rewrite PA4, Calculate a Cell Phone Bill, to ask
the user if they want to repeat the program after
the bill and savings are output. Also put the
input validation in a loop.