You are on page 1of 29

Flow chart and Pseudocode for Repetition

Introduction
Repetition control structures
while dowhile for

The Essentials of Repetition


Loop
Group of instructions the computer executes repeatedly while some loop-continuation condition remains true

Counter-controlled repetition
Definite repetition; i.e., number of repetitions is known Control variable is used to count repetitions and incremented (or decremented) each time the group of instructions is performed

Sentinel-controlled repetition
Indefinite repetition; i.e., number of repetitions is not known in advance Sentinel value indicates end of data
It must be distinct from regular data items

Counter-controlled Repetition
Counter-controlled repetition requires
The name of a control variable (or loop counter) The initial value of the control variable The condition that tests for the final value of the control variable (when looping should terminate) The increment (or decrement) by which the control variable is modified each time through the loop

The while Repetition Structure


Repetition structures
Used to repeat specific actions while some condition remains true

The while repetition structure


Repeat specific actions while some condition remains true Syntax: Placing a semicolon here
while ( condition ) statement would generate a logic error!

How does it work?


while loop is repeated until condition becomes false statement is executed when while loop repeats

In other words, while loop is repeated as long as condition remains true

The while Repetition Structure


Example:
Write a program segment that finds the first power of 2 larger than 1000 Pseudocode:
initialize product to 2 while product is less than or equal to 1000 int product = 2; Names product, set product = 2 * product

Code in Java:
int product = 2; while ( product <= 1000 ) { product = 2 * product; } Braces are not required if there is
only one statement in the body of the while structure, but it is good programming practice to use them

declares it to be an integer and sets it to an initial value of 2

product is the control variable of this while loop Avoid using floating-point numbers as the control variable!

The while Repetition Structure


Flowchart of the while structure:
True
condition False

statement

Example:
product <= 1000 False True

In this example, when product equals 1024, condition will fail and while loop terminates
product = 2*product

The do/while Repetition Structure


The do/while repetition structure
Rather similar to the while structure Condition for repetition tested after the body of the loop is performed
All actions are performed at least once

It is different from the while structure because


In the while structure, the condition is tested at the beginning of the loop before body is performed

Syntax:
do { statement } while ( condition );

Good programming practice to put braces to avoid misinterpreted as a while statement containing an empty statement Not placing a semicolon here would generate a syntax error!

The do/while Repetition Structure


Example:
Write a program that prints the numbers from 1 to 10 Code in C: Declares an integer named
counter, and sets it to int counter = 1; an initial value of 1 do { System.out.print(counter + ); counter is the } while ( ++counter <= 10 ); control variable of

this do/while loop

Braces are not required if there is only one statement in the body of the do/while structure, but it is good programming practice to use them

What happens if you change the expression at last line of the code to while (counter++ <= 10);
1 2 3 4 5 6 7 8 9 10 11

The do/while Repetition Structure


Flowchart of the do/while structure:
statement
condition False Note that the condition is not tested until after actions (or statements) are performed once

True

Example:
print counter ++counter <= 10 True

False

The for Repetition Structure


The for repetition structure
Handles all the details of counter-controlled repetition automatically

Syntax:
statement

Placing a semicolon here would generate a logic error!

for ( expression1 ; expression2 ; expression3 )

How does it work?


When the for structure begins executing, expression1 initializes the loops control variable At the beginning of the loop, the loop-continuation condition in expression2 is examined At the end of the loop, expression3 adjusts (e.g., increments or decrements) the loops control variable

The for Repetition Structure


Example:
Write a program that prints the even numbers from 2 to 100 Code in Java:
Control variable name Initial value of control variable Final value of control variable for which the condition is true Increment of control variable

for (number = 2; number <= 100; number += 2) { System.out.print (number); Loop continuation condition }
Braces are not required if there is only one statement in the body of the for structure, but it is good programming practice to use them No semicolon after the last expression!

The for Repetition Structure


Flowchart of the for structure:
expression1 expression2 False

True

statement

expression3
Adjustment of the control variable is done at the end of the loop

Example:
Loopcontinuation test is done at the beginning of the loop
number = 2

Initialization of the control variable when the for structure begins executing (performed only once)
True print number

number <= 100

number += 2

False

How many times will this loop be executed?

Notes on the for Repetition Structure


for loops can usually be rewritten as while loops
Syntax:
expression1; while ( expression2 ) { statement expression3; }

Compare with:
for (number=2; number<=100; number+=2) { System.out.print( number + \t); }

Example:

int number = 2; while ( number <= 100 ) { System.out.print( number + \t); number += 2; }

Notes on the for Repetition Structure


Initialization and increment (or decrement) can be comma-separated list
To allow for multiple initialization and/or multiple increment (or decrement) expressions Example:
for ( i = 0, j = 0; i+j <= 10; i++, j++ )

System.out.print(i+j );
What is the output of this code?
Note the comma here
0 2 4 6 8 10

Increment (or decrement) expression in the for structure is tested at the end of the body of the loop, so postincrement (e.g., k++) and preincrement (e.g., ++k) have the same effect but usually postincrement is used to make it more natural.

Notes on the for Repetition Structure


The 3 expressions in the for structure are optional
If expression2 is omitted, C will assume that the condition is always true; i.e., infinite loop expression1 may be omitted if the control variable is initialized elsewhere (before the for structure) expression3 may be omitted if the control variable is adjusted elsewhere in the body of the for structure, e.g., at the end of the loop

Notes on the for Repetition Structure


Arithmetic expressions
Initialization, loop-continuation, and increment (or decrement) can contain arithmetic expressions Example:
If x equals 2 and y equals 10, then for (j = x; j <= 4*x*y; j += y/x) is equivalent to for (j = 2; j <= 80; j += 5)

Final notes
If loop-continuation condition is initially false
The body of the for structure is not executed Control proceeds with the next statement after the for structure

Control variables are usually used inside the body of the loop

Notes on the for Repetition Structure


More examples:
Vary the control variable from 1 to 100:
for (i = 1; i <= 100; i++)

Vary the control variable from 100 to 1 in decrements of 1:


for (i = 100; i >= 1; i--)

Vary the control variable from 7 to 77 in steps of 7:


for (i = 7; i <= 77; i += 7)

Vary the control variable over the sequence:


99, 88, 77, 66, 55, 44, 33, 22, 11, 0 for (i = 99; i >= 0; i -= 11)

Example 1: Counter-controlled Repetition


Counter-controlled repetition
Definite repetition; i.e., number of repetitions is known Loop is repeated until counter reaches a certain value

Problem:
A class of ten students took a quiz. The grades (integers in the range of 0 to 100) for this quiz are available to you. Determine the class average on the quiz. Pseudocode:
initialize total to 0 Initialization of variables initialize counter to 1 Uninitialized variable while counter is less than or equal to 10 contains a garbage value. input next grade Using them will probably add grade into total produce incorrect results. increment counter by 1 This is an example of the set the average to the total divided by 10 non-fatal logic (or runtime) print the average error.

Example 1: Counter-controlled Repetition


Problem (cont.) Flowchart:
START total = 0 counter = 1

Initialization is performed only once

Body of the loop can consist of a single statement, compound statement, or even an empty statement; in the case of the compound statement, braces are required

counter <= 10 False

True

input grade total = total + grade

counter++

average = total/10 print average END

Loop-continuation test is done at the beginning of the loop

Adjustment of the control variable is done at the end of the loop

Example 2: Sentinel-controlled Repetition


Sentinel-controlled repetition
Indefinite repetition; i.e., number of repetitions is not known in advance Sentinel value indicates the end of data

Problem:
Generalize Example 1 to an unknown number of students Develop a class-averaging program that will process an arbitrary number of grades each time the program is run. How will the program knows when to end?
Using sentinel value; also known as signal value, dummy value, or flag value Indicates end of data entry Loop ends when user inputs the sentinel value Sentinel value must be chosen so that it cannot be confused with the regular input (such as 1 in this example)

Example 2: Sentinel-controlled Repetition


Top-down, stepwise refinement to develop program
Top level outline of problem:
determine the class average for the quiz

Divide problem into smaller tasks and list them in order (first refinement):
initialize the variables input, sum and count the quiz grades calculate and print the average

Proceed to the next level of refinement -- commit to specific variables (second refinement):
Many programs can be divided logically into 3 phases: Initialization: Initializes the program variables Processing: Inputs data values and adjusts program variables accordingly Termination: Calculates and prints final results This helps the breakup of programs for top-down refinement

Example 2: Sentinel-controlled Repetition


Refine the initialization phase from initialize the variables to:
initialize total to 0 initialize counter to 0

Refine the processing phase from input, sum and count the quiz grades to:
input the first grade (possibly the sentinel) while the user has not as yet entered the sentinel add this grade into the running total increment counter by 1 input the next grade (possibly the sentinel)

Refine the termination phase from calculate and print the average to: To prevent the

if the counter is not equal to 0 fatal divide by set the average to the total divided by the counter zero error! print the average else print No grades were entered."

Example 3: Nested Control Structures


Problem:
A college has a list of exam results (value 1 for pass, value 2 for fail) for 10 students. Write a program that analyzes the results such that if more than 8 students passed, print Raise tuition. Notice that:
The program must process 10 exam results Counter-controlled loop will be used Three counters will be used One each for the number of students, the number of passes, the number of failures Each exam result is a number, either a 1 or a 2 If the number is not a 1, we will assume that it is a 2 After processing all the results, the program must decide if more than 8 students passed the exam

Example 3: Nested Control Structures


Top-down, stepwise refinement to develop program
Top level outline of problem:
analyze the results and decide if tuition should be raised

Divide problem into smaller tasks and list them in order:


initialize the variables input the 10 quiz grades and count the number of passes and failures print a summary of the results and decide if tuition should be raised

Second refinement:
Refine initialize the variables to: initialize student counter to 1 initialize passes to 0 initialize failures to 0

Example 3: Nested Control Structures


Refine input the 10 quiz grades and count the number of passes and failures to: while student counter is less than or equal to 10 input the next exam result if the student passed if/else structure increment passes by 1 nested inside the else while structure increment failures by 1 increment student counter Refine print a summary of the results and decide if tuition should be raised to: print the number of passes print the number of failures if more than 8 students passed print Raise tuition.

Summary on Programming
Rules for programming
Developed by the programming community Only single-entry/single-exit control structures are used Rules:
1) Begin with the simplest flowchart 2) Stacking rule: Any rectangle (action) symbol can be replaced by two other rectangle (action) symbols in sequence 3) Nesting rule: Any rectangle (action) symbol can be replaced by any control structure (sequence, if, if/else, switch, while, do/while, for) 4) Rules 2 and 3 can be applied in any order and any number of times

Summary on programming
Rule 1: Begin with the simplest flowchart

Rule 2 (Stacking Rule): Any rectangle (action) symbol can be replaced by two rectangle symbols in sequence

Summary on programming
F T

Rectangle replaced by an if/else structure

Rule 3 (Nesting Rule): Any rectangle (action) symbol can be replaced by any control structure

What are these new structures?


T F

T F

Summary on programming
Rules for programming
All programs can be broken down into 3 controls
Sequence: Handled automatically by the compiler Selection: if, if/else, or switch Repetition: while, do/while, or for

Any selection can be rewritten as an if statement, and any repetition can be rewritten as a while statement

The control structures can only be combined in 2 ways


Stacking (as in Rule 2), and Nesting (as in Rule 3)

You might also like