Lesson 4 Progress
0%
Lesson 4  ยท  Loops

for, while, do-while

Repeat actions without repeating code. Loops are how programs process lists, count, sum, search, and build patterns.

for loop
while loop
do-while
break & continue
Nested loops
๐Ÿ“–

Why Loops?

Without loops, to print 1 to 100 you would write 100 printf statements. With a loop, you write 3 lines. Loops let you repeat a block of code automatically โ€” as many times as needed.

  • for โ€” best when you know exactly how many times to repeat
  • while โ€” best when you repeat until a condition becomes false
  • do-while โ€” same as while but always runs at least once
LoopChecks conditionMinimum runsBest for
forBefore each run0Counting: 1 to 10, table of 5
whileBefore each run0Reading until 0, processing digits
do-whileAfter each run1 alwaysMenus, input retry
example 1
1

Multiplication Table Generator

for loop

for loop โ€” three parts in one line

int i = 1
โ‘  Init โ€” runs once
;
i <= 10
โ‘ก Condition โ€” checked each time
;
i++
โ‘ข Update โ€” after each loop

The user enters a number and the program prints its complete multiplication table. The for loop starts at 1, goes to 10, and the counter i is used both as the multiplier and in the output.

Example 1 ยท times_table.c
times_table.c
C
#include <stdio.h>

int main() {
    int n;

    printf("Enter a number: ");
    scanf("%d", &n);

    printf("\n--- Multiplication Table of %d ---\n", n);

    for (int i = 1; i <= 10; i++) {
        printf("%d x %2d = %d\n", n, i, n * i);
    }

    return 0;
}
terminal โ€” n=7
output
--- Multiplication Table of 7 ---
7 x  1 = 7
7 x  2 = 14
7 x  3 = 21
...
7 x 10 = 70
๐Ÿ’ก %2d prints the integer in a field of width 2 โ€” so single-digit numbers align with double-digit ones. Makes the table look neat.
example 2
2

Monthly Savings Tracker

while loop + accumulator

Uses a while loop to keep reading monthly savings amounts until the user enters 0. An accumulator variable adds up the total. This is the classic pattern for processing unknown amounts of input.

Example 2 ยท savings.c
savings.c
C
#include <stdio.h>

int main() {
    float amount, total = 0;
    int   months = 0;

    printf("Enter monthly savings (0 to stop):\n");
    scanf("%f", &amount);

    while (amount != 0) {
        total  += amount;
        months += 1;
        printf("Month %d saved: Rs %.2f  |  Total: Rs %.2f\n",
               months, amount, total);
        scanf("%f", &amount);
    }

    printf("\n--- Summary ---\n");
    printf("Months tracked : %d\n",     months);
    printf("Total savings  : Rs %.2f\n", total);

    if (months > 0)
        printf("Monthly average: Rs %.2f\n", total / months);

    return 0;
}
terminal
output
3000
Month 1 saved: Rs 3000.00  |  Total: Rs 3000.00
4500
Month 2 saved: Rs 4500.00  |  Total: Rs 7500.00
2800
Month 3 saved: Rs 2800.00  |  Total: Rs 10300.00
0
--- Summary ---
Months tracked : 3
Total savings  : Rs 10300.00
Monthly average: Rs 3433.33
example 3
3

PIN Entry with 3 Attempts

do-while + counter

A do-while is perfect here โ€” the PIN prompt must show at least once. The loop repeats until the correct PIN is entered or 3 attempts are used up. A counter tracks how many tries remain.

Example 3 ยท pin_entry.c
pin_entry.c
C
#include <stdio.h>

int main() {
    int pin, attempts = 0;
    int correct_pin = 4729;   // stored PIN
    int max_attempts = 3;
    int success = 0;

    do {
        attempts++;
        printf("Enter PIN (attempt %d/%d): ", attempts, max_attempts);
        scanf("%d", &pin);

        if (pin == correct_pin) {
            success = 1;   // flag correct entry
        } else {
            printf("โœ— Wrong PIN. ");
            if (attempts < max_attempts)
                printf("%d attempt(s) left.\n", max_attempts - attempts);
        }

    } while (!success && attempts < max_attempts);

    printf("\n");
    if (success)
        printf("โœ“ Access granted! Welcome.\n");
    else
        printf("โœ— Card blocked. Too many wrong attempts.\n");

    return 0;
}
terminal โ€” wrong then right
output
Enter PIN (attempt 1/3): 1111
โœ— Wrong PIN. 2 attempt(s) left.
Enter PIN (attempt 2/3): 4729
โœ“ Access granted! Welcome.

Enter PIN (attempt 1/3): 0000
โœ— Wrong PIN. 2 attempt(s) left.
Enter PIN (attempt 2/3): 1234
โœ— Wrong PIN. 1 attempt(s) left.
Enter PIN (attempt 3/3): 9999
โœ— Card blocked. Too many wrong attempts.
example 4
4

Prime Number Checker

for loop + break

A prime number has no divisors other than 1 and itself. We use a for loop with break โ€” as soon as we find one divisor we stop immediately. A flag variable isPrime tracks whether any divisor was found.

Example 4 ยท prime_check.c
prime_check.c
C
#include <stdio.h>

int main() {
    int n, isPrime = 1;

    printf("Enter a number: ");
    scanf("%d", &n);

    if (n < 2) {
        isPrime = 0;   // 0 and 1 are not prime
    } else {
        for (int i = 2; i < n; i++) {
            if (n % i == 0) {     // found a divisor
                isPrime = 0;
                break;             // no need to keep checking
            }
        }
    }

    if (isPrime)
        printf("%d is PRIME\n", n);
    else
        printf("%d is NOT prime\n", n);

    // Bonus: print all primes up to n
    printf("\nAll primes up to %d: ", n);
    for (int num = 2; num <= n; num++) {
        int ok = 1;
        for (int i = 2; i < num; i++)
            if (num % i == 0) { ok = 0; break; }
        if (ok) printf("%d ", num);
    }
    printf("\n");

    return 0;
}
terminal
output
Enter: 17  โ†’  17 is PRIME
             All primes up to 17: 2 3 5 7 11 13 17

Enter: 12  โ†’  12 is NOT prime
             All primes up to 12: 2 3 5 7 11
๐Ÿ’ก break exits the innermost loop immediately. Once we know n has a divisor, there is no point checking more. The break saves unnecessary iterations and makes the program faster.
example 5
5

Number Pyramid Pattern

Nested for loops

Nested loops โ€” a loop inside a loop. The outer loop controls rows, the inner loop controls columns. For every single iteration of the outer loop, the inner loop runs completely from start to finish.

Example 5 ยท pyramid.c
pyramid.c
C
#include <stdio.h>

int main() {
    int rows;

    printf("Enter number of rows: ");
    scanf("%d", &rows);

    printf("\n--- Number Pyramid ---\n");
    for (int i = 1; i <= rows; i++) {
        // Print spaces for centering
        for (int s = 1; s <= rows - i; s++)
            printf(" ");

        // Print numbers counting up
        for (int j = 1; j <= i; j++)
            printf("%d ", j);

        printf("\n");
    }

    printf("\n--- Star Triangle ---\n");
    for (int i = 1; i <= rows; i++) {
        for (int j = 1; j <= i; j++)
            printf("* ");
        printf("\n");
    }

    printf("\n--- Inverted Star ---\n");
    for (int i = rows; i >= 1; i--) {
        for (int j = 1; j <= i; j++)
            printf("* ");
        printf("\n");
    }

    return 0;
}
terminal โ€” rows=5
output
--- Number Pyramid ---
    1
   1 2
  1 2 3
 1 2 3 4
1 2 3 4 5

--- Star Triangle ---
*
* *
* * *
* * * *
* * * * *

--- Inverted Star ---
* * * * *
* * * *
* * *
* *
*
๐Ÿ’ก Total iterations = outer ร— inner. For rows=5: star triangle runs 5+4+3+2+1 = 15 inner iterations. Number pyramid adds a space loop โ€” 3 separate inner loops per outer row.
quiz
Q

Quick Quiz

Question 1 of 4

How many times does for(int i=1; i<=5; i++) run?

Question 2 of 4

Which loop GUARANTEES running at least once even if the condition is false from the start?

Question 3 of 4

What does continue do inside a for loop?

Question 4 of 4

Outer loop runs 4 times, inner loop runs 3 times. Total iterations of inner loop body?

โœ“

Lesson Checklist

  • I know the 3 parts of a for loop: init, condition, update
  • I can use a for loop to print a multiplication table
  • I understand while checks condition BEFORE running body
  • I can use while to accumulate values until a sentinel (0) is entered
  • I understand do-while runs body first then checks condition
  • I know break exits the loop immediately
  • I know continue skips the current iteration only
  • I understand nested loops โ€” inner ร— outer = total runs
  • I can write a star or number pattern using nested loops
  • I completed the quiz