Malik_05
Malik_05
3 4
5 6
1
Flowchart view of while loop
b) Post-test: do…while
enter a score
• General form of the do…while loop
False True do
is score != -1? {
iterative part;
Add score to total
}
while(loop-test); // notice the semicolon.
Enter another score
Iterative • First time, program drops into the do portion with no loop-
test.
output total score Part
• loop-test is evaluated after the first iteration.
• if loop-test is false, program drops out and continues.
• if true, returns to the first iterative statement after do.
7 8
Note: Notice that the iterative part will be done at least once in a
do-while loop. False
Note: There is a semi-colon after the while.
output total score
9 10
11 12
2
When to use the do-while loop Example do-while loop
– The do while loop is a good choice for obtaining char option;
interactive input from menu selections. do
– Consider a function that won't stop executing until {
the user enters an N, O, or S: cout << "Enter N)ew, O)pen, S)ave: ";
cin >> option;
option = toupper(option); // from cctype
// if option is one of the choices do something accordingly.
}
while (option !='N‘ && option != 'O‘ && option != 'S');
(this loop continues only if an invalid option is entered. Eg. ‘P’)
13 14
15 16
17 18
3
computePay.cc computePay.cc
while (empCount < numberEmp) Program Output
{ Enter number of Employees: 3
cout << "Hours: ";
cin >> hours; Hours: 50
cout << "Rate : $"; Rate: $15.25
cin >> rate; Pay is: $762.50
pay = hours * rate; Hours: 6
cout << "Pay is " << pay << endl << endl; Rate: $12.50
totalPay += pay; //do you see why we need initial value?
empCount++; Pay is: $75
} Hours: 1.5
cout << "Total payroll is " << totalPay << endl; Rate: $9.25
Pay is: $13.88
cout << "All employees processed." << endl; Total payroll is $851.38
return 0; All employees processed.
}
19 20
21 22
23 24
4
eof controlled while Loops eof Function
• end-of-file (eof)-controlled while loop: when • The function eof can determine the end of
it is difficult to select a sentinel value file status.
• the eof character is CTRL-D on the key board • eof is a member of data type istream
(cin) and in files is automatically found at the • Syntax for the function eof:
end of file.
• The logical value returned by cin can • istreamVar is an input stream variable,
determine if there is no more input. such as cin
25 26
sumScores.cc sumScores.cc
while (score != SENTINEL)
// File: sumScores.cc {
// Accumulates the sum of exam scores. sum += score;
#include <iostream> count++;
using namespace std; if(score >= 90)
const int SENTINEL = -1; cout << “\tGrade is: ‘A’” << endl;
int main() else if(score >= 80) . . .
cout << endl<< "Enter the next score: ";
{ cin >> score;
int score, sum, count, average; }
// Process all exam scores until sentinel is read cout << endl << endl;
count = 0; cout << "Number of scores processed is " << count << endl;
sum = 0; cout << "Sum of exam scores is " << sum << endl;
cout << "Enter scores one at a time as requested." << endl; // Compute and display average score.
cout << "When done, enter " << SENTINEL << " to stop." << endl; if (count > 0)
cout << "Enter the first score: "; {
average = sum / count;
cin >> score; cout << "Average score is " << average;
}
return 0;
}
29 30
5
// FILE: largest.cc
// FINDS THE LARGEST NUMBER IN A SEQUENCE OF INTEGER VALUES
sumScores.cc #include <iostream> // needed for cin and cout
using namespace std;
const int MIN_VALUE = -32768; // smallest possible integer in given data
Program Output int main ()
Enter the scores one at a time as requested. {
When done, enter -1 to stop. // Local data ...
int itemValue; // each data value
Enter the first score: 55 int largestSoFar; // largest value so far
Grade is ‘C’
// Initialize largestSoFar to the smallest integer.
Enter the next score: 33 largestSoFar = MIN_VALUE;
Grade is ‘D’ do
Enter the next score: 77 {
cout << "Enter a integer, " << MIN_VALUE-1 << " to stop: ";
Grade is ‘B’ cin >> itemValue;
Enter the next score: -1 if (itemValue > largestSoFar)
largestSoFar = itemValue;
}
Sum of exam scores is 165 while (itemValue != MIN_VALUE);
3 exam scores were processed. cout << "The largest value entered was " << largestSoFar << endl;
return 0;
Average of the exam scores is 55.0 }
31 32
33 34
6
Another for loop Flow chart for a for loop
for(int i=0; i<10; i++)
countEmp = 0
cout << i << “ squared = “ << i * i << endl;
False True
Notice: there are no { } in the body of the for loop since is countEmp < 7?
37 38
for looping (repetition) structure (cont’d.) for looping (repetition) structure (cont’d.)
39 40
for looping (repetition) structure (cont’d.) for looping (repetition) structure (cont’d.)
41 42
7
Nested Loops Nested while-loop
• It is possible to nest loops outer = 1;
while(outer <= 3)
– Loops go inside other loops {
int inner = 1; // Resets for each iteration of the outer loop
– Start with outer jump to inner loop while(inner <= outer)
{
– Inner loop continues until completed cout << outer << " " << inner << endl;
inner = inner + 1; // End of the nested loop
– Control goes back to outer loop and then inner }
loop starts all over again outer = outer + 1; // Increment the outer loop counter
} // End of the outer loop Program output
11
21
22
31
32
33
43 44
45 46
47 48
8
Programming Example: Fibonacci Number Programming Example. Fibonacci Numbers algorithm
Problem: Find first 10 fibonacci numbers
• Consider the following sequence of numbers:
1, 1, 2, 3, 5, 8, 13, 21, 34, .... • enter first two fib seq numbers into n1, n2
• Called the Fibonacci sequence • repeat the following 4 steps 8 times:
• Given the first two numbers of the sequence • set temp = n1 + n2
(say, a1 and a2) • output temp;
– nth number an, n >= 3, of this sequence is given by: • set n1 = n2;
an = an-1 + an-2 • set n2 = temp;
• Write a program to output the first 10 fib seq. • output "good bye"
numbers given the first 2
49 50
51 52
53 54
9
Avoiding Bugs by Avoiding Patches Debugging Loops
• Loops are harder to debug than sequence and
• Software patch selection structures
– Piece of code written on top of an existing piece • Most common error associated with loops is
of code off-by-one
– Intended to fix a bug in the original code – for(int i=0; i<5; i++) will loop 5 times
• Some programmers address the symptom of – for(int i=0; i<=5; i++) loops 6 times
the problem by adding a software patch – most often we use the former so if we want to
• Should instead resolve underlying issue loop 6 times use for(int i=0; i<6; i++)
– every convention has its exceptions.
55 56
57 58
59 60
10
Programming Error Helpful Hints
– Coding style and use of braces.
– Infinite loops will “hang you up !!”
– Use comments before and after a loop. This helps to see if
you went into the loop and exited it.
– Test various conditions of loops.
– Add white space between code segments.
– Initialize looping variables inside the for loop. It will not be
recognized outside the loop.
– eg. for(int i = 0; i<4; i++)
cout << i << “. Hello” << endl;
cout << i << endl;
// results in compile error. i is only meant as an index and has
no other meaning.
61
11