Beruflich Dokumente
Kultur Dokumente
LOOPS
Chapter 7
Concept of Repetition Structure Logic
Average()
1. Real Sum, Average
2. Sum = St1_Grade+St2_Grade+St3_Grade+ St4_Grade+St5_Grade+St6_Grade+ St7_Grade
3. Average = Sum/ 7
4. Exit
Solution with looping structure
Average()
Real Student_Grade 1. Integer Count=1
Control () 2. Real Sum=0
3. While ( count <= 7)
1. Read() 1. Read()
2. Average() 2. Sum=Sum +Student_Grade
3. Count=Count+1
3. End 4. WhileEnd
5. Real Average = Sum / count
6. Exit
Read()
1. Enter Student_Grade
2. Exit
Average Module Algorithm Flowchart
Flowchart
What will
Happen If What will
Average()
we Happen If Sum has no initial
remove we
this? value, its value is
Integer Count=1 remove
this?
Unknown
Real Sum=0
Count has no
data, its value is F T
While
Unknown, So the Count<=7
value of the
condition is Read() What will
unpredictable. Happen If
Real Average = Sum / 7 we
Sum=Sum+Student_Grade
remove
this?
Exit Count=Count+1
Count = 100
Incrementing (or Decrement)
Is done by adding a constant , such as 1 or 2 to the
value of a variable
Example :
Counter = counter + 1 or c=c+1
Note: Remember Variable Must be
Initialized before starting the loop.
Examples:
Totalsales = Totalsales + Sales
Repeat
Instruction
Instruction
.
.
.
Until< Condition(S)>
Example 1:
While/WhileEnd Repeat/Until
•You must initialize the data so that the •You can set the operand of the conditions
resultant of the condition is true the first anywhere within the loop since the
time through the loop. Otherwise , the loop condition is processed at the end .
instruction will never be processed . •Repeat the loop until the resultant of
•Repeat the loop until the resultant of condition is true.
condition is false. •The condition is processed at the end
•The condition is processed at the beginning •Instructions in the loop are processed
entirely at least once.
Automatic-Counter Loop
Increments or decrements a variable each time the
loop is repeated .
Use it when you know from the start the number of
times the loop will be executed .
The beginning value , the ending value , and the
increment value may be constant , variable , or
expressions .
Automatic-Counter Loop
Variable name
Loop: counter=begin To End Step S
Instruction
Instruction
Instruction
.
.
Loop –End: Counter
Automatic-Counter Loop:
General Rules
When the computer executes the Loop instruction its sets the
counter equal to the beginning number.
3 ( J -1 )
4 J,
5
( J – 1)
J,
Example 2:
Create the algorithm & flowchart to:
Prints the even numbers.
The series of numbers will:
Start From 0 .
Ends at 50.
Example 2 Solution
Algorithm
PrintEvenNum()
1. Loop: counter=0 To 50 Step 2
1. Print counter
2. Loop-End: counter
3. End
Recursion
Another type of loop structure .
A module or a function calls itself .
Example :
FactorialFunction (N)
1. If N > 1
then
Factorial = N * FactorialFunction (N-1)
Else
Factorial = 1
2. Exit