0% found this document useful (0 votes)
8 views11 pages

Malik_05

The document discusses the concept of iteration in programming, specifically focusing on control structures for repetition in C++. It explains various looping constructs such as while loops, do...while loops, and for loops, detailing their syntax and use cases. Additionally, it covers topics like sentinel and flag-controlled loops, infinite loops, and provides examples to illustrate these concepts.

Uploaded by

Ahmed Al-nasheri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views11 pages

Malik_05

The document discusses the concept of iteration in programming, specifically focusing on control structures for repetition in C++. It explains various looping constructs such as while loops, do...while loops, and for loops, detailing their syntax and use cases. Additionally, it covers topics like sentinel and flag-controlled loops, infinite loops, and provides examples to illustrate these concepts.

Uploaded by

Ahmed Al-nasheri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Iteration (repetition)

• Iteration: process of repeating certain


Control Structures II statements over and over again.
(Repetition, Chpt 5) • Iteration avoids writing same statements
again and again.
Chapter 5

The need for iteration Repetitive control structures


• Add 5 numbers and find their average: – Many algorithms require numerous iterations over the
cin >> num1 >> num2 >> num3 >> num4 >> num5; same statements. Eg.
• To average 100 numbers, we would need 300 plus statements.
sum = num1 + num2 + num3 + num4 + num5; • Or we use a statement that has the ability to loop or repeat a
average = static_cast<double>(sum)/5.0; collection of statements.
• This is doable but what if we want to do the same for 100 – C++ has three repetition or looping structures:
a) while loop
numbers? b) do…while loop
• A real chore, messy and not desirable! c) for loop
• There is a much easier and neater way! – The while and for loops are known as a pre-test loops.
– The do…while is known as a post-test loop.

3 4

a) Pre-test: while Loop Pre-Test: While loop


Example: find total of some positive test scores.

– General form of the while statement: int total = 0, score;


cout << “Enter test score (-1 to stop): “;
while ( loop-test ) cin >> score;
while(score != -1)
{ {
iterative-part total = total + score;
cout << “Enter score (-1 to stop): “;
} cin >> score;
}
– loop-test is evaluated first. If true, do the iterative part, cout << “ The total score is “ << total << endl;
then do loop-test again. Note1: There should always be a way for a loop to stop
– Process continues until the loop-test becomes false. Note2: The iterative parts may never be done. This is
why it is called a pre-test
– Need a statement to make loop-test false. Otherwise Note 3: This is a sentinel controlled loop (-1).
we can’t get out of while loop.

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

Flowchart of do-while loop


Post-test: do…while loop
Example: find the total of some positive test scores. Enter a score

const int SENTINEL = -1;


int total = 0; int score; Yes
do is score != -1?
Iterative add score to total
{
cout << “Enter score (-1 to stop): “; Part
cin >> score; No
if(score >=0)
total += score;
}
while (score != SENTINEL); True
cout << “ The total score is “ << total << endl; is score != -1

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

do…while Looping structure (con’t.) do…while Looping (Repetition) Structure (cont’d.)

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

which is better? Infinite loops


• in some instances you may want to use a while loop.
• in some instances you may want to use a do…while loop.
• you decide, there is no right answer. – Infinite loop: a loop that never terminates.
• but you can see that they can do the same things as in the – you won’t see your prompt again. Hit CTRL-C to get the
prior programs illustrating them. prompt back.
• What are the trade offs? – Infinite loops are usually not desirable unless you are
– Some while loop needs two prompts for data, no if statement. running a clock or an ATM banking machine.
– Some do…while loops needs only one prompt for data but need an if
statement inside iteration. – Infinite loops are caused when the loop-test never gets set
• some situations lend themselves better to while loops, some to false.
to do…while loops.
• practice helps.

15 16

Example of an infinite loop


computePay.cc
int cntr = 0;
while (cntr < 10)
{ // FILE: computePay.cc
cout << “Hello there” << endl; // COMPUTES THE PAYROLL FOR A COMPANY using a loop
} structure
cout << "Do we ever get here?" << endl; #include <iostream>
using namespace std;
There is no step that brings (cntr<10) to false. int main ()
(Notice that there are parentheses around the single statement in this while {
loop. As with the if statement, there is no need for parentheses when there is int numberEmp, empCount;
only one executable statement.) double hours;
double rate, pay, totalPay;
How do we fix the infinite loop? Add cntr++; statement below the cout.
while (cntr < 10) // Get number of employees from user.
{ cout << "Enter number of employees: ";
cout << “Hello there” << endl; cin >> numberEmp;
cntr++;
} // Compute each employee's pay and add it to the payroll.
totalPay = 0.0; // set initial value
Note: There are many ways to get into an infinite loop so you need to trace empCount = 0;
your loop steps when it happens.

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

Sentinel vs flag controlled loop Sentinel Controlled


• A sentinel is a special value that marks the end int sum = 0, num;
cout << “Enter positive number, -1 to quit: “;
of a list of values cin >> num;
• A flag is a boolean variable that signals when a while(num != -1) // -1 signals the end of the list (sentinel)
condition exists. {
sum += num;
cout << “Enter positive number, -1 to quit: “;
cin >> num;
}
cout << “The sum is: “ << sum << endl;

21 22

Loop Design and Loop Patterns


Flag controlled • sentinel-controlled loops
1. Read the first data item.
// code to test if user enters a digit character. 2. while the sentinel value has not been read
char nextChar; 3. Process the data item.
4. Read the next data item.
bool digitRead = false; // digitRead is the flag
while(!digitRead) // while the flag is not true…repeat… • flag controlled loops
{ 1. Set the flag to false (or true)
2. while the flag is false (or true)
cout << “Please enter a character: “; 3. Perform some action.
cin >> nextChar; 4. Reset the flag to true (or false) if the anticipated event occurred.
digitRead = (nextChar >= ‘0’ && nextChar <= ‘9’); • eof controlled loops
} 1. Read the first data item
cout << “The digit entered was: ” << nextChar <<endl; 2. while the end-of-file has not been detected
… 3. Process the data item
4. Read the next data item

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

This program displays a list of numbers an their squares.


#include <iostream>
eof-controlled while loops (con’t) using namespace std;
const int MIN_NUMBER = 1; const int MAX_NUMBER = 10;
int cntr = 0, total=0, number; int main( )
double average; { int num = MIN_NUMBER;
cout << “Enter some numbers (CTRL-D) to quit: "; cout << "Number Squared\n";
cin >> number; cout << "-------------------------\n";
while(!cin.eof( )) while(num <= MAX_NUMBER)
{ {
total += number; cout << "_ _ _" << num << "_ _ _ _ _ _ _ _ _" << num * num << endl;
cntr++; num++;
cin >> number; // need new number before eof() is tested again. } Output:
} return 0; Number Squared
average = static_cast<double>(total)/cntr; } ------------------------
1 1
cout << "The total is: " << endl;
2 4
cout << "The average is: " << average << endl;
3 9

10 100
27 28

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

Largest.cc c) The for Statement


Program Output – The for loop is similar to the while loop.
– The for loop forces us to write, as part of the for
Finding the largest value in a sequence:
loop:
Enter an integer or -32769 to stop: -999
Enter an integer or -32769 to stop: 500
a) an initializing statement,
Enter an integer or -32769 to stop: 100 b) the loop-test,
Enter an integer or -32769 to stop: -32769 c) a statement that is automatically repeated for each
The largest value entered was 500 iteration, usually a variable increment stmt.
– a for loop is like a while loop in that it is a pre-
test loop.

33 34

General form of a for loop Eg: for-loop


for( initial statement; loop-test; repeated statement)
{
iterative part
– This for-loop is counter controlled.
} – Scope of the loop control variable, cntr, is local
– When a for loop is encountered, within the “for” block.
a. the initial statement is executed. for(int cntr=1; cntr<=5; cntr++)
b. The loop-test is evaluated.
c. If the loop-test is false, the for loop is terminated and exits to
{
the point below the loop. cout << cntr << " ";
d. otherwise the iterative part is executed. }
e. the repeated statement is executed.
cout << endl;
f. go to step b. and continue.
Note the semicolons, not commas! • Output: ?
35 36

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?

there is only one statement.


Get Data
Compute Pay
Display Pay
Increase countEmp by 1

37 38

for looping (repetition) structure (cont’d.) for looping (repetition) structure (cont’d.)

• The following is a semantic error:

• The following is a legal (but infinite) for loop:


for (;;)
cout << "Hello" << endl;

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

Nested for-loops Program Output


// FILE: nestedForLoops.cc i j
#include <iostream> Outer 0
#include <iomanip> Outer 1
int main () Inner 0
{ Outer 2
// display heading Inner 0
cout << setw(12) << "i" << setw(6) << "j" << endl; Inner 1
for (int i = 0; i < 4; i++) Outer 3
{ Inner 0
cout << "Outer" << setw (7) << i << endl; Inner 1
for (int j = 0; j < i; j++) Inner 2
cout << " Inner" << setw (10) << j << endl;
}
return 0;
}

45 46

Nested Control Structures Conditional Loops


• To create the following pattern:
***** • When you don’t know the number of iterations
***** use a while or a do-while loop.
*****
***** • When you know the number of iterations use a
***** for loop. eg logarithm table or a table of powers.
• We can use the following code:
for (i = 1; i <= 5 ; i++)
{
for (j = 1; j <= 5; j++)
cout << "*";
cout << endl;
}

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

A different Fibonacci version Choosing the Right Looping Structure


• ask user which fibonacci number to get, n
• All three loops have their place in C++
• ask user for first two fib numbers, n1,n2 – If you know or can determine in advance the
• repeat the following n steps n-2 times number of repetitions needed, the for loop is
• set temp = n1 + n2; the correct choice
– If you do not know and cannot determine in
• set n1 = n2;
advance the number of repetitions needed, and it
• set n2 = temp; could be zero, use a while loop
• cout << "the <n>th fib # is " << temp; – If you do not know and cannot determine in
advance the number of repetitions needed, and it
is at least one, use a do...while loop

51 52

break and continue statements


break and continue statements (cont’d.)
• break and continue alter the flow of
control • continue is used in while, for, and
• break statement is used for two purposes: do…while structures
– To exit early from a loop • When executed in a loop
• Can eliminate the use of certain (flag) variables – It skips remaining statements and proceeds with
– To skip the remainder of a switch structure the next iteration of the loop
• After break executes, the program continues
with the first statement after the structure

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

Summary Summary (cont’d.)


• C++ has three looping (repetition) structures: • while: logical expression is the
– while, for, and do…while decision maker, and statements are the
• while, for, and do are reserved words body of the loop
• while and for loops are called pretest loops • A while loop can be:
• do...while loop is called a posttest loop – Counter-controlled
• while and for may not execute at all, but – Sentinel-controlled
do...while always executes at least once – eof-controlled
• In the UNIX console environment, the end-of-
file marker is entered using Ctrl+d

57 58

Debugging and Testing Programs


Summary (cont’d.)
• for loop: simplifies the writing of a counter- • Modern Integrated Development
controlled while loop Environments (IDEs) include features to help
– Putting a semicolon at the end of the for loop is
you debug a program while it is executing.
a semantic error. • If you cannot use a debugger, insert extra
• Executing a break statement in the body of a diagnostic output statements to display
loop immediately terminates the loop. intermediate results at critical points in your
program.
• Executing a continue statement in the body
of a loop skips to the next iteration.

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

You might also like