Iterations in Programming
Iterations in Programming
Chapter: 7
▪ Condition – controlled loop – when you do not know how many times you need to repeat the loop. -
need to set a logical test
– the result of the test tells the computer whether to repeat the loop.
Note:
Every loop must have an exit condition. The exit condition is a logical test that tells the computer when to
stop repeating the loop.
Write a pseudocode to input a value by a user and multiply and print the value with the
number of iterations using counter - controlled loop.
DECLARE Value : INTEGER # Declaration of Variable named Value OUTPUT “ Enter a value ” # Prompt
INPUT Value # take input from user and store in variable Value FOR counter ← 1 TO 4 # this loop will
iterate five times, OUTPUT “Value is ” , Value * counter # multiply a value entered by user with # of
OUTPUT “The loop has stopped.” # prints the output statement after loop ends. MAA - Aitchison College - Lahore
Exercise: Write a pseudocode to input 10 numbers and find the total and average using
counter controlled loop.
DECLARE Number: INTEGER
Total 🡨 0 // initialize the variable Total
FOR counter ← 0 TO 10
Number 🡨 INPUT “ Enter a positive number "
Total 🡨 Total + Number
NEXT counter
Average 🡨 Total / 10
TOTALLING
Adding a new value into previous value
Total 🡨 Total + NewValue
Example:-
Input 10 numbers from user and output total and average of 10 numbers.
DECLARE Num, Count, Total: INTEGER
Total 🡨 0
FOR Count 🡨 1 to 3
Num 🡨 INPUT “Enter a number”
Total 🡨 Total + Num
NEXT Count
Average 🡨 Total/ 10
OUTPUT “Total of entered 10 numbers is”, Total
OUTPUT “Average of entered 10 numbers is”, Average
MAA - Aitchison College - Lahore 7
COUNTING
Adding 1 in previous value
Count 🡨 Count + 1
Example:-
Input 10 numbers from user and output how many numbers were greater then
50 DECLARE Num, Count, GreaterCount : INTEGER
GreaterCount 🡨 0
FOR Count 🡨 1 to 3
INPUT “Enter a number”, Num
IF Num > 50 THEN
GreaterCount🡨 GreaterCount +1
END IF
NEXT Count
OUTPUT “Numbers greater then 50 are” , MAA GreaterCount - Aitchison College - Lahore 8
<statements>
ENDWHILE
while <Logical test>: Python uses a colon to show the start of
the while loop and indentation to show
<statements>
which statements are in the while loop.
REPEAT Pseudocode
<statements>
UNTIL <condition>
There is no REPEAT … UNTIL Loop statements in Python
MAA - Aitchison College - Lahore
9
Example (Pre-condition loop) Language
Number 🡨 1 Pseudocode
Number 🡨 1 Pseudocode
REPEAT
OUTPUT Number
Number 🡨 Number + 1
UNTIL Number > 10