Algorithms with Loops and Branching
What Are Loops and Branching?
- Loops and branching are fundamental concepts in programming that allow algorithms to make decisions and repeat actions.
- Loops are used to repeat a set of instructions multiple times.
- Branching allows an algorithm to choose between different paths based on conditions.
- These constructs help solve problems efficiently by reducing repetition and enabling dynamic behavior.
Think of loops as a washing machine cycle that repeats until the clothes are clean, and branching as the decision to use hot or cold water based on the fabric type.
More formal terms for loops and branching are iteration ans selection respectively.
Types of Loops
For Loops
- For loops are used when the number of iterations is known in advance.
- They are often used to iterate over a range of values or elements in a collection.
Printing numbers from 1 to 5 using a for loop.
for i in range(1, 6):
print(i)Or in IB pseudocode:
loop I from 1 to 5
output I
end loop- Usually, for loop is exclusive to the last iteration, that is, Python loop for i in range(1, 5) will produce values for i: 1, 2, 3, 4 (without 5).
- However, in IB pseudocode loop I from 1 to 5, values 1, 2, 3, 4, 5 (with 5) will be assigned.
Use for loops when you know exactly how many times you need to repeat an action.
While Loops
- While loops are used when the number of iterations is not known in advance.
- The loop continues as long as a specified condition is true.
Printing numbers from 1 to 5 using a while loop.
i = 1
while i <= 5:
print(i)
i = i + 1In IB pseudocode:
I = 1
loop while I <= 5
output I
I = I + 1
end loopA common mistake is creating an infinite loop by not updating the loop variable or condition.
Repeat-until loops
- Repeat-until loops are similar to while loops but guarantee that the loop body executes at least once.
- The loop continues until a specified condition becomes true.
Printing numbers from 1 to 5 using a repeat-until loop.
i = 1
while True:
print(i)
i = i + 1
if i > 5: # Stop when i > 5
breakUse repeat-until loops when you need the loop to run at least once, regardless of the condition.
Branching
If-else statements allow algorithms to choose between two paths based on a condition.
Example: Checking if a number is even or odd.
N = 5
if N mod 2 = 0 then
output "Even"
else
output "Odd"
end ifElse-if statements extend if-else statements to handle multiple conditions.
Grading students score on a test:
POINTS = 85
if POINTS >= 90 then
output "Grade A"
else if POINTS >= 40 then
output "Grade B"
else
output "Grade C"
end ifAvoid overlapping conditions in else-if statements to prevent logical errors.
Combining Loops and Branching
Some real-world examples include:
- Bubble sort uses nested loops to compare and swap elements until the list is sorted.
- Allowing a user three attempts to enter the correct password.
- Filtering out invalid entries in a list of user data.
Printing even numbers from 1 to 10.
loop N from 1 to 10
if N mod 2 = 0 then
output N
end if
end loopCombining loops and branching allows you to create more complex and dynamic algorithms.
To help understand how such algorithm works, you can draw flow chart.
- Try to solve following exercises:
- Write an algorithm that prints the first 10 Fibonacci numbers.
- Create a flowchart for an algorithm that checks if a number is prime.
- Write a pseudo-code algorithm that calculates the factorial of a number using a while loop.
- Explain the difference between for loops and while loops. When would you use each?
- Identify and fix the error in the following code
I = 1
loop while I < 5
output I
end loop