1.02

Loops and Repetition

Learn how to repeat actions using loops. Master `for` and `while` loops to write efficient code.

Learning Objectives:

  • β€’Understand what loops are and why they matter
  • β€’Write simple `for` loops
  • β€’Write simple `while` loops
  • β€’Count and iterate over ranges
Prerequisites: Display and Output (Level 1, Chapter 1)
Estimated Time: 30 min

Why Loops?

Imagine you want to print "Hello" 100 times. You could write:

python
print("Hello") print("Hello") print("Hello") # ... 97 more times

But that's tedious and error-prone. Loops let you repeat code automatically.

The for Loop

A for loop repeats a block of code a specific number of times:

python
for i in range(5): print(i)

This prints:

plaintext
0 1 2 3 4

The variable i starts at 0 and increments each time, up to (but not including) 5.

The while Loop

A while loop repeats while a condition is true:

python
count = 0 while count < 5: print(count) count = count + 1

This produces the same output as the for loop above. The loop continues as long as count < 5.

Nested Loops

You can put loops inside loops to create patterns:

python
for i in range(3): for j in range(2): print(f"i={i}, j={j}")

Output:

plaintext
i=0, j=0 i=0, j=1 i=1, j=0 i=1, j=1 i=2, j=0 i=2, j=1

Key Syntax in Different Languages

Python:

python
for i in range(5): print(i) while count < 5: count = count + 1

C/C++/Java:

c
for (int i = 0; i < 5; i++) { printf("%d\n", i); } while (count < 5) { count = count + 1; }

JavaScript:

javascript
for (let i = 0; i < 5; i++) { console.log(i); } while (count < 5) { count = count + 1; }

Practice Exercises

Exercise 2.1 β€” Count to 10

Objective: Use a loop to print numbers 1 through 10, each on a new line.

Output:

plaintext
1 2 3 4 5 6 7 8 9 10

Exercise 2.2 β€” Multiplication Table

Objective: Print the 5 times table (5Γ—1, 5Γ—2, ..., 5Γ—10).

Output:

plaintext
5 10 15 20 25 30 35 40 45 50

Exercise 2.3 β€” Rectangle Pattern

Objective: Use nested loops to draw a rectangle of * characters.

For a 4Γ—3 rectangle (4 wide, 3 tall):

plaintext
**** **** ****

Hints

Stuck? Try these hints:

  1. Free: Nested loops have an outer loop and an inner loop. The inner loop completes fully before the outer loop moves to the next iteration.
  2. Hint 2 (5 XP): Check your loop bounds β€” are you starting and ending at the right numbers?
  3. Hint 3 (10 XP): For the rectangle, the outer loop controls rows, the inner loop controls columns.

Key Takeaways

  • for loops repeat a fixed number of times
  • while loops repeat while a condition is true
  • Nested loops let you create 2D patterns and complex repetitions
  • Loops are fundamental to solving real programming problems

Progress: 2/8 chapters complete in Level 1 βœ“