You are on page 1of 5

As level Programming

Loops
Iteration
Repeat the same steps no of times controlled by a condition.
There are 3 types of loops:

• Pre-condition loop – WHILE loop


• Post-condition loop- REPEAT loop
• Counter controlled loop – FOR loop

WHILE Loop
• Entering the loop only if the given condition is TRUE
EX: Take 10 integer inputs from the user and output the total.

declare num,count,total:integer
count ← 0
total ← 0
WHILE count< 10
OUTPUT "enter the integer number: "
INPUT num
total ← total + num
count ← count + 1
ENDWHILE
OUTPUT total

1
START

count ← 0
total ← 0

No
count< 10

yes

OUTPUT "enter the integer


number: "

INPUT num number: "

total ← total + num

count ← count + 1

OUTPUT total

END

2
Q)
1. Take 10 integer inputs from the user and output the total number of odd values and
even values separately.
2. Take integer inputs until the user enter 5 odd numbers.

REPEAT Loop
• Keep iterating until a given condition becomes TRUE

declare num,count,total:integer
count ← 0
total ← 0
REPEAT
OUTPUT "enter the number: "
INPUT num
total ← total + num
count ← count + 1
UNTIL count=10
OUTPUT total

END

count ← 0
total ← 0

OUTPUT "enter the number: "

INPUT num

total ← total + num


count ← count + 1

yes
If count=10
No
OUTPUT total

END

3
• Rogue value: a value used to terminate a repetition. It should be same data type of the
variable but out of the expected value range.
Q)
1. Take integer inputs from the user until the user enter -1. Output the total of the
input numbers.

FOR LOOP
Structure
FOR count← initializing_value TO limit STEP n
<statements>
ENDFOR

• Step syntax is optional


• Instead of ‘TO’ syntax, the syntax ‘DOWNTO’ can be used to decrease the count in a FOR
LOOP

Eg: The loop will continue for a given number of times. Controlled by a counter
variable.

declare count,num,total:integer

total ← 0
FOR count←1 to 5
OUTPUT "enter an integer: "
INPUT num
total ← total + num
ENDFOR
OUTPUT total

4
START

total ← 0

count ← 1

OUTPUT "enter the number: "

INPUT num
count ← count + 1

total ← total + num

YES
If count<5

NO

OUTPUT total

END

You might also like