Chapter 7: Loops in C

C gives us three main types of loops:

  • for loop
  • while loop
  • do…while loop

We will also learn nested loops, break, and continue.

1. for Loop

Best when you know how many times you want to repeat (fixed number of times).

Syntax:

C
  • Initialization: Runs once (usually declare and set counter)
  • Condition: Checked before every iteration
  • Update: Runs after every iteration (usually increment/decrement)

Example: Print numbers 1 to 10

C

Output:

text

Another Example: Sum of first 10 natural numbers

C

Output:

text

2. while Loop

Best when you don’t know exactly how many times the loop will run – you repeat while a condition is true.

Syntax:

C

Example: Keep asking for password until correct

C

3. do…while Loop

Similar to while, but guarantees at least one execution – code runs first, then condition is checked.

Syntax:

C

Example: Menu that keeps showing until user exits

C

Key Difference:

  • while → checks condition first (may never run)
  • do…while → runs at least once, checks condition after

4. Nested Loops

A loop inside another loop – very useful for tables, patterns, 2D arrays, etc.

Example: Print multiplication table from 1 to 5

C

Output (partial):

text

5. break and continue Statements

break → Immediately stops the loop and jumps out

continue → Skips the current iteration and goes to next one

Example: Print numbers 1 to 10, but skip 5 and stop at 8

C

Output:

text

Summary Table – When to Use Which Loop

Loop Type Best For Checks Condition Runs at Least Once?
for Known number of times Before No
while Unknown number of times Before No
do…while Unknown, but must run at least once After Yes

Today’s Homework

  1. Write a program using for loop to print all even numbers from 1 to 50.
  2. Write a while loop program that keeps asking the user for numbers until they enter 0 – then print the sum of all entered numbers.
  3. Create a do…while loop that shows a calculator menu (add, subtract, multiply, divide, exit) and performs operations until user chooses exit.
  4. Print this pattern using nested loops:
    text
  5. Write a program that prints numbers 1 to 20, but skips multiples of 3 (use continue) and stops if number reaches 15 (use break).

You may also like...