Document 4
Document 4
Introduction to Loops
Loops allow us to repeat a block of code multiple times without rewriting it.
There are three main types of loops:
2. FOR Loop
The FOR loop is used when we know exactly how many times we need to
execute a set of instructions.
Pseudocode Syntax:
Pseudocode:
FOR i FROM 1 TO 5 DO
OUTPUT i
ENDFOR
Python Code:
Pseudocode:
sum <- 0
FOR i FROM 1 TO 10 DO
sum <- sum + i
ENDFOR
OUTPUT sum
Python Code:
sum = 0
for i in range(1, 11):
sum += i
print(sum)
Pseudocode:
Python Code:
Pseudocode:
FOR i FROM 1 TO 5 DO
OUTPUT i * i
ENDFOR
Python Code:
Pseudocode:
FOR i FROM 1 TO 3 DO
OUTPUT "Hello"
ENDFOR
Python Code:
for i in range(3):
print("Hello")
3. WHILE Loop
The WHILE loop runs as long as a condition is TRUE. The condition is checked
before executing the loop body.
Pseudocode Syntax:
WHILE condition DO
// Statements to execute
ENDWHILE
Pseudocode:
num <- 1
WHILE num <= 5 DO
OUTPUT num
num <- num + 1
ENDWHILE
Python Code:
num = 1
while num <= 5:
print(num)
num += 1
Example 2: Print even numbers up to 10
Pseudocode:
num <- 2
WHILE num <= 10 DO
OUTPUT num
num <- num + 2
ENDWHILE
Python Code:
num = 2
while num <= 10:
print(num)
num += 2
Pseudocode:
Python Code:
Pseudocode:
num <- 3
count <- 1
WHILE count <= 5 DO
OUTPUT num
num <- num + 3
count <- count + 1
ENDWHILE
Python Code:
num = 3
count = 1
while count <= 5:
print(num)
num += 3
count += 1
Pseudocode:
num <- 10
WHILE num >= 1 DO
OUTPUT num
num <- num - 1
ENDWHILE
Python Code:
num = 10
while num >= 1:
print(num)
num -= 1
4. REPEAT…UNTIL Loop
This loop ensures that the block of code executes at least once, and then
repeats until the condition is TRUE.
The REPEAT UNTIL loop ensures that the code inside it runs at least once,
regardless of the condition. After the first execution, the loop will continue to
repeat until the specified condition becomes TRUE. This makes it different
from the WHILE loop, which checks the condition before executing the loop
body.
Pseudocode Syntax:
REPEAT
// Statements to execute
UNTIL condition
Pseudocode:
REPEAT
num <- USERINPUT
UNTIL num = 0
while True:
num = int(input("Enter a number: "))
if num == 0:
break
Pseudocode:
num <- 1
REPEAT
OUTPUT num
num <- num + 1
UNTIL num > 5
Python Code:
num = 1
while True:
print(num)
num += 1
if num > 5:
break
5. Summary
FOR loops are best for a known number of iterations.
WHILE loops are best when we don’t know how many times we need to
run the loop beforehand.
REPEAT UNTIL loops guarantee at least one execution and stop when
the condition becomes true.
Practice Questions:
1. Write a REPEAT UNTIL loop to take input from the user until they enter
a valid password (e.g., "pass123").
2. Write a REPEAT UNTIL loop to keep asking for a positive number until
the user enters one.
3. Write a WHILE loop to keep taking user input until they enter a
negative number.
4. Write a WHILE loop to calculate the sum of digits of a given number.