Examples Progress
0%
Lesson 4  ·  Extra Examples

Loops — 5 More Examples

Five unique programs using for, while, do-while, break, and continue. Each one solves a different real-world problem using loops.

E1

Fibonacci Series Generator

for loop + two variables

The Fibonacci series is 0, 1, 1, 2, 3, 5, 8, 13... — each number is the sum of the two before it. We use a for loop and swap variables each iteration. A classic algorithm implemented cleanly with a loop.

Example E1 · fibonacci.c
fibonacci.c
C
#include <stdio.h>

int main() {
    int n;

    printf("How many Fibonacci numbers? ");
    scanf("%d", &n);

    int a = 0, b = 1, next;

    printf("Fibonacci Series: ");

    for (int i = 1; i <= n; i++) {
        printf("%d ", a);
        next = a + b;   // next = sum of previous two
        a = b;          // shift: a becomes b
        b = next;       // b becomes the new number
    }
    printf("\n");

    // Also check if input n is in the series
    int x, p = 0, q = 1;
    printf("Enter a number to check if it is Fibonacci: ");
    scanf("%d", &x);

    while (p < x) { int t = p + q; p = q; q = t; }

    if (p == x || x == 0)
        printf("%d IS a Fibonacci number!\n", x);
    else
        printf("%d is NOT a Fibonacci number.\n", x);

    return 0;
}
terminal
output
How many Fibonacci numbers? 8
Fibonacci Series: 0 1 1 2 3 5 8 13

Enter a number to check: 8
8 IS a Fibonacci number!

Enter a number to check: 9
9 is NOT a Fibonacci number.
💡 Variable swap pattern: next = a+b; a = b; b = next; — this three-line swap is used in many algorithms. Always store the new value first before overwriting.
example 2
E2

Reverse a Number & Palindrome Check

while loop + modulus

Uses the % and / operators inside a while loop to extract digits one by one from right to left. Then builds the reversed number by multiplying. If the reverse equals the original — it's a palindrome number!

Example E2 · reverse_palindrome.c
reverse_palindrome.c
C
#include <stdio.h>

int main() {
    int n, original, reversed = 0, digit;

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

    while (n != 0) {
        digit    = n % 10;           // extract last digit
        reversed = reversed * 10 + digit; // append to reversed
        n        = n / 10;           // remove last digit
    }

    printf("Original : %d\n", original);
    printf("Reversed : %d\n", reversed);

    if (original == reversed)
        printf("%d is a PALINDROME number!\n", original);
    else
        printf("%d is NOT a palindrome.\n", original);

    return 0;
}
terminal
output
Enter: 121  →  Reversed: 121  →  PALINDROME! ✓
Enter: 1331 →  Reversed: 1331 →  PALINDROME! ✓
Enter: 1234 →  Reversed: 4321 →  NOT a palindrome.
example 3
E3

Count Vowels & Consonants

for loop + continue

Loops through each character of a string. Uses continue to skip spaces. Demonstrates how loops process arrays character by character — a fundamental string processing technique.

Example E3 · vowel_count.c
vowel_count.c
C
#include <stdio.h>
#include <string.h>

int main() {
    char str[100];
    int  vowels = 0, consonants = 0;

    printf("Enter a word or sentence: ");
    fgets(str, sizeof(str), stdin);  // reads full line

    for (int i = 0; i < strlen(str); i++) {
        char c = str[i];

        // Skip spaces and newline
        if (c == ' ' || c == '\n') continue;

        // Check if vowel (upper or lower case)
        if (c=='a'||c=='e'||c=='i'||c=='o'||c=='u'||
            c=='A'||c=='E'||c=='I'||c=='O'||c=='U') {
            vowels++;
        } else if ((c>='a'&&c<='z')||(c>='A'&&c<='Z')) {
            consonants++;
        }
    }

    printf("Vowels     : %d\n", vowels);
    printf("Consonants : %d\n", consonants);
    printf("Total chars: %d\n", vowels + consonants);

    return 0;
}
terminal
output
Enter: Hello World
Vowels     : 3
Consonants : 7
Total chars: 10

Enter: Ananta Creative
Vowels     : 7
Consonants : 8
Total chars: 15
example 4
E4

Compound Interest Year-by-Year

for loop + float accumulation

Shows bank balance growing year by year with compound interest. The for loop repeats the interest calculation for each year, updating the balance each time. A practical finance program that demonstrates how loops model real-world growth.

Example E4 · compound_interest.c
compound_interest.c
C
#include <stdio.h>

int main() {
    float principal, rate, balance;
    int   years;

    printf("Enter principal amount (Rs): ");
    scanf("%f", &principal);

    printf("Enter annual interest rate (%%): ");
    scanf("%f", &rate);

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

    balance = principal;

    printf("\n%-6s  %-12s  %-12s\n",
           "Year", "Interest", "Balance");
    printf("--------------------------------\n");

    for (int y = 1; y <= years; y++) {
        float interest = balance * rate / 100;
        balance += interest;
        printf("%-6d  Rs %-9.2f  Rs %.2f\n",
               y, interest, balance);
    }

    printf("--------------------------------\n");
    printf("Final balance : Rs %.2f\n", balance);
    printf("Total earned  : Rs %.2f\n", balance - principal);

    return 0;
}
terminal — 10000 at 8% for 5 years
output
Principal: 10000  Rate: 8%  Years: 5

Year    Interest      Balance
--------------------------------
1       Rs 800.00     Rs 10800.00
2       Rs 864.00     Rs 11664.00
3       Rs 933.12     Rs 12597.12
4       Rs 1007.77    Rs 13604.89
5       Rs 1088.39    Rs 14693.28
--------------------------------
Final balance : Rs 14693.28
Total earned  : Rs 4693.28
example 5
E5

Number Guessing Game

do-while + hints

A complete interactive game using do-while. The secret number is hardcoded (in real programs it would use rand()). The loop keeps asking for guesses and gives "higher" or "lower" hints until the player guesses correctly. Counts attempts.

Example E5 · guessing_game.c
guessing_game.c
C
#include <stdio.h>

int main() {
    int secret = 42;    // the number to guess
    int guess, attempts = 0;

    printf("=== NUMBER GUESSING GAME ===\n");
    printf("Guess the number between 1 and 100!\n\n");

    do {
        printf("Your guess: ");
        scanf("%d", &guess);
        attempts++;

        if      (guess < secret) printf("📈 Too low!  Try higher.\n");
        else if (guess > secret) printf("📉 Too high! Try lower.\n");
        else                     printf("🎉 Correct!\n");

    } while (guess != secret);

    printf("\n--- RESULT ---\n");
    printf("You guessed %d in %d attempt(s).\n", secret, attempts);

    if      (attempts == 1)  printf("🏆 Perfect! First try!\n");
    else if (attempts <= 5)  printf("⭐ Excellent! Very few tries!\n");
    else if (attempts <= 10) printf("👍 Good effort!\n");
    else                      printf("😅 Keep practising!\n");

    return 0;
}
terminal — sample game
output
=== NUMBER GUESSING GAME ===
Guess a number between 1 and 100!

Your guess: 50  →  📉 Too high! Try lower.
Your guess: 25  →  📈 Too low!  Try higher.
Your guess: 37  →  📈 Too low!  Try higher.
Your guess: 42  →  🎉 Correct!

--- RESULT ---
You guessed 42 in 4 attempt(s).
⭐ Excellent! Very few tries!
💡 do-while is perfect for games and menus. The game prompt must show at least once. With do-while, the body always runs first, then the condition (guess != secret) is checked. The loop only ends when they match.
examples checklist

Examples Checklist

  • E1 — I can generate Fibonacci using a for loop and variable swapping
  • E2 — I can reverse a number using while loop with % and /
  • E2 — I understand the palindrome check — reversed == original
  • E3 — I can loop through a string character by character
  • E3 — I used continue to skip spaces in the string loop
  • E4 — I can use a for loop to accumulate compound interest year by year
  • E5 — I can build a complete interactive game with do-while
  • I completed all 5 example programs