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.
NoteMore 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.
Tip
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