Professional Documents
Culture Documents
LOOPING / ITERATIVE
Loops and Counter
§ Looping
§ Used when it is desired to make the same calculation of more than
one set of data. It consists of repeating a program, or a section of
program and substituting new data for each repetition.
§ Counter
§ Is a setup in a program loop to keep track of a number of times the
program segment is repeated. The program can then be terminated
after the completion of a predetermined number of passes.
Loops and Counter
§ Steps in Loop Control
§ Initialization
§ The value of counter is initially set equal to zero or one.
§ Test for limit condition
§ Before the logic flow gets out of a loop, a loop terminating condition must first
be satisfied.
§ Incrementation
§ Often each loop is executed, 1 is added to the counter. Thus counter reflects
the number of times the operation has been performed.
Looping / Iterative – for loop
§ Pseudo code
§ Method 1 Method 2
FOR i = r to s by 1 do FOR (i = r ; i<=s ; i++)
statements
statements
ENDFOR ENDFOR
Example
§ Example
FOR i =1 to 5 by 1 then FOR( i =1 ; i<=s; i++)
PRINT: i
PRINT: i
ENDFOR
ENDFOR
3. Repeat step 3
Execute Statements
2. else
CALCULATE: i = i +1
1. END
END
Example for Looping
§ The initial value of the radius of a circle is equal to one unit
and each succeeding radius is one unit greater than the
values before it. Make a pseudo-code and draw a flowchart
to compute the area of the circle starting with R=1.0 up to
R=5.0, then print out each radius and corresponding area of
the circle.
Programming
LOOPING / ITERATIVE
Pretest Loops
§ In each iteration, the control
expression is tested first.
§ If it is true, the loop action(s) are
executed;
§ Examples:
§ The loop will exit if the user entered a negative number.
§ The loop ends when the sum is already equal to 100.
Counter-Controlled Loops
§ If the number of repetition is known, the counter-controlled
loop is used.
§ Examples:
§ Display your name n times.
§ Display the number from 1 to n.
Loops in C
Loop Statements
§ Syntax:
initialization
while(terminating_expression)
{
body of the loop;
update;
}
initialization
do {
body of the loop;
update;
}while(terminating_expression);