-->

C Programming Day 5 : Loops in C – for, while & do-while, Beginner to Advanced

C Programming Day 5

C Programming Day 5 Loops in C for while do while flowchart


    Introduction

    Welcome to Day 5 of the C Programming Full Course.

    In the previous lesson, we learned how to make decisions using conditional statements such as if, if-else, nested if, else-if, and switch.

    But what happens when we need to execute the same block of code repeatedly?

    For example:

    • Print numbers from 1 to 100
    • Display a multiplication table
    • Calculate the sum of numbers
    • Process multiple student records
    • Generate patterns
    • Repeat a menu until the user exits
    • Read multiple values from the user

    Writing the same statement hundreds of times would be inefficient.

    This is where loops in C become extremely useful.

    A loop allows a program to execute a block of code repeatedly as long as a specified condition is satisfied.

    In this lesson, you'll learn:

    • What loops are
    • Why loops are important
    • for loop
    • while loop
    • do-while loop
    • Nested loops
    • break statement
    • continue statement
    • Infinite loops
    • Practical programs
    • Common mistakes
    • Interview questions
    • Practice exercises


    What is a Loop in C?

    A loop is a programming structure that repeatedly executes a block of statements while a condition is true.

    Simple Example

    Suppose you want to print:

    Hello C Programming

    five times.

    Without a loop:

    printf("Hello C Programming\n");
    printf("Hello C Programming\n");
    printf("Hello C Programming\n");
    printf("Hello C Programming\n");
    printf("Hello C Programming\n");

    With a loop:

    for(int i = 1; i <= 5; i++)
    {
        printf("Hello C Programming\n");
    }

    The loop makes the program shorter, cleaner, and easier to maintain.


    Why Are Loops Important in C?

    Loops are one of the most important concepts in programming.

    They are used for:

    • Repeating calculations
    • Processing arrays
    • Reading multiple inputs
    • Searching data
    • Generating patterns
    • Creating menus
    • Mathematical calculations
    • File processing
    • Game development
    • Data processing
    • Algorithm implementation

    Almost every significant C program uses loops in some form.


    Types of Loops in C

    C provides three primary looping statements:

    Loop                         Description

    for                       Best when the number of iterations is known

    while                   Best when repetition depends on a condition

    do-while              Executes the loop body at least once


    The basic structure is:

            Start
              ↓
          Check Condition
           ↙          ↘
        True             False
          ↓                    ↓
     Execute Code   End
          ↓
     Update
          ↓
     Check Again


    for Loop in C

    The for loop is commonly used when you know approximately how many times you want to execute a block of code.

    Syntax

    for(initialization; condition; update)
    {
        // statements
    }

    It has three main parts:

    Initialization

    Runs once before the loop begins.

    int i = 1;

    Condition

    Checked before each iteration.

    i <= 10;

    Update

    Changes the loop variable.

    i++;

    Example 1: Print Numbers from 1 to 10

    #include <stdio.h>

    int main()
    {
        int i;

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

        return 0;
    }

    Output

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10

    How the for Loop Works

    The execution happens in this order:

    i = 1
     ↓
    i <= 10?
     ↓
    Print i
     ↓
    i++
     ↓
    Check condition again

    When i becomes 11, the condition becomes false and the loop stops.

    Example 2: Print Even Numbers

    #include <stdio.h>

    int main()
    {
        int i;

        for(i = 2; i <= 20; i += 2)
        {
            printf("%d ", i);
        }

        return 0;
    }

    Output

    2 4 6 8 10 12 14 16 18 20

    Example 3: Print Odd Numbers

    #include <stdio.h>

    int main()
    {
        int i;

        for(i = 1; i <= 20; i += 2)
        {
            printf("%d ", i);
        }

        return 0;
    }

    Example 4: Countdown

    #include <stdio.h>

    int main()
    {
        int i;

        for(i = 10; i >= 1; i--)
        {
            printf("%d\n", i);
        }

        printf("Start!");

        return 0;
    }

    Example 5: Multiplication Table

    #include <stdio.h>

    int main()
    {
        int n, i;

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

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

        return 0;
    }

    If the user enters 5:

    5 x 1 = 5
    5 x 2 = 10
    5 x 3 = 15
    5 x 4 = 20
    5 x 5 = 25
    5 x 6 = 30
    5 x 7 = 35
    5 x 8 = 40
    5 x 9 = 45
    5 x 10 = 50


    while Loop in C

    The while loop executes a block of code as long as a condition is true.

    Syntax

    while(condition)
    {
        // statements
    }

    The condition is checked before the loop body executes.

    Therefore, a while loop is called a pre-test loop.

    Example 1: Print Numbers from 1 to 10

    #include <stdio.h>

    int main()
    {
        int i = 1;

        while(i <= 10)
        {
            printf("%d\n", i);

            i++;
        }

        return 0;
    }

    How the while Loop Works

    Initialize i
        ↓
    Check condition
        ↓
    Condition true?

       YES
        ↓
    Execute statements
        ↓
    Update i
        ↓
    Check condition again

       NO
        ↓
       End

    Example 2: Sum of Numbers

    #include <stdio.h>

    int main()
    {
        int i = 1;
        int sum = 0;

        while(i <= 10)
        {
            sum = sum + i;
            i++;
        }

        printf("Sum = %d", sum);

        return 0;
    }

    Output

    Sum = 55

    Example 3: User-Controlled Loop

    #include <stdio.h>

    int main()
    {
        int number;

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

        while(number != 0)
        {
            printf("You entered: %d\n", number);

            printf("Enter another number (0 to stop): ");
            scanf("%d", &number);
        }
        printf("Program ended.");

        return 0;
    }

    This type of loop is useful when you don't know beforehand how many times the loop needs to run.


    do-while Loop in C

    The do-while loop is similar to the while loop, but there is one important difference.

    The body of a do-while loop executes at least once, even if the condition is initially false.

    Syntax

    do
    {
        // statements
    }
    while(condition);

    Notice the semicolon after the condition:

    while(condition);

    Example

    #include <stdio.h>

    int main()
    {
        int i = 1;

        do
        {
            printf("%d\n", i);
            i++;
        }
        while(i <= 10);

        return 0;
    }


    Important Difference Between for, while & do-while

    Consider:

    int i = 20;

    while(i <= 10)
    {
        printf("%d", i);
    }

    The body executes zero times.

    But:

    int i = 20;

    do
    {
        printf("%d", i);
    }
    while(i <= 10);

    The body executes one time.

    Output:

    20

    That's the key difference between while and do-while.

    Example: Menu-Driven Program

    A do-while loop is very useful for menus.

    #include <stdio.h>

    int main()
    {
        int choice;

        do
        {
            printf("\n===== MENU =====\n");
            printf("1. Add\n");
            printf("2. Subtract\n");
            printf("3. Exit\n");

            printf("Enter choice: ");
            scanf("%d", &choice);

            switch(choice)
            {
                case 1:
                    printf("Addition selected.");
                    break;

                case 2:
                    printf("Subtraction selected.");
                    break;

                case 3:
                    printf("Exiting...");
                    break;

                default:
                    printf("Invalid choice.");
            }
        }
        while(choice != 3);

        return 0;
    }

    This is a practical example of combining:

    • do-while
    • switch
    • break
    • User input

    for vs while vs do-while

    Feature                           for                             while                       do-while
    Condition                Before execution         Before execution      After execution
    Minimum executions     0                               0                                             1
    Best use                  Known iterations             Unknown iterations     Menu/input systems
    Initialization         Usually inside loop            Usually before loop     Usually before loop
    Update               Usually inside loop expression  Inside body                   Inside body

    When Should You Use Each Loop?

    Use for when:

    You know how many times the loop should run.

    Example:

    for(i = 1; i <= 100; i++)

    Use while when:

    The number of iterations depends on a condition.

    Example:

    while(password != correctPassword)

    Use do-while when:

    The code needs to execute at least once.

    Example:

    do
    {
        displayMenu();
    }
    while(choice != 0);


    Nested Loops

    A loop inside another loop is called a nested loop.

    Example:

    for(i = 1; i <= 3; i++)
    {
        for(j = 1; j <= 3; j++)
        {
            printf("* ");
        }
        printf("\n");
    }

    Output

    * * *
    * * *
    * * *

    The outer loop controls the rows, while the inner loop controls the columns.

    Example: Multiplication Table Grid

    #include <stdio.h>

    int main()
    {
        int i, j;
        for(i = 1; i <= 5; i++)
        {
            for(j = 1; j <= 5; j++)
            {
                printf("%d\t", i * j);
            }
            printf("\n");
        }
        return 0;
    }

    Example: Star Pattern

    #include <stdio.h>

    int main()
    {
        int i, j;
        for(i = 1; i <= 5; i++)
        {
            for(j = 1; j <= i; j++)
            {
                printf("* ");
            }
            printf("\n");
        }
        return 0;
    }

    Output

    *
    * *
    * * *
    * * * *
    * * * * *


    break Statement

    The break statement immediately terminates a loop.

    Example

    #include <stdio.h>

    int main()
    {
        int i;
        for(i = 1; i <= 10; i++)
        {
            if(i == 6)
            {
                break;
            }
            printf("%d ", i);
        }
        return 0;
    }

    Output

    1 2 3 4 5

    When i becomes 6, break terminates the loop.


    continue Statement

    The continue statement skips the remaining statements in the current iteration and moves to the next iteration.

    Example

    #include <stdio.h>

    int main()
    {
        int i;
        for(i = 1; i <= 10; i++)
        {
            if(i == 5)
            {
                continue;
            }
            printf("%d ", i);
        }
        return 0;
    }

    Output

    1 2 3 4 6 7 8 9 10

    The number 5 is skipped.

    break vs continue

    break                                   continue

    Terminates the loop              Skips current iteration

    Exits the loop completely    Continues with next iteration

    Used to stop execution         Used to skip specific cases


    Infinite Loop

    An infinite loop is a loop that never ends because its condition always remains true.

    Example:

    while(1)
    {
        printf("Hello\n");
    }
    Another example:
    for(;;)
    {
        printf("Running...");
    }

    Infinite loops can be useful in certain applications, such as servers and embedded systems, but they can also be caused accidentally.

    Common Cause

    int i = 1;
    while(i <= 10)
    {
        printf("%d", i);
    }

    The value of i never changes.

    Therefore, the condition remains true forever.

    Correct version:

    int i = 1;
    while(i <= 10)
    {
        printf("%d", i);
        i++;
    }


    Real-World Programs Using Loops

    Program 1: Calculate Factorial

    The factorial of 5 is:

    5 × 4 × 3 × 2 × 1 = 120

    C Program

    #include <stdio.h>

    int main()
    {
        int n, i;
        long long factorial = 1;
        printf("Enter a number: ");
        scanf("%d", &n);
        for(i = 1; i <= n; i++)
        {
            factorial = factorial * i;
        }
        printf("Factorial = %lld", factorial);
        return 0;
    }

    Program 2: Reverse a Number

    #include <stdio.h>

    int main()
    {
        int number;
        int reverse = 0;
        int remainder;
        printf("Enter a number: ");
        scanf("%d", &number);
        while(number != 0)
        {
            remainder = number % 10;
            reverse = reverse * 10 + remainder;
            number = number / 10;
        }
        printf("Reverse = %d", reverse);
        return 0;
    }

    Program 3: Count Digits

    #include <stdio.h>

    int main()
    {
        int number;
        int count = 0;
        printf("Enter a number: ");
        scanf("%d", &number);
        while(number != 0)
        {
            number = number / 10;
            count++;
        }
        printf("Number of digits = %d", count);
        return 0;
    }

    Program 4: Sum of Digits

    #include <stdio.h>

    int main()
    {
        int number;
        int sum = 0;
        int digit;
        printf("Enter a number: ");
        scanf("%d", &number);
        while(number != 0)
        {
            digit = number % 10;
            sum = sum + digit;
            number = number / 10;
        }
        printf("Sum of digits = %d", sum);
        return 0;
    }

    Program 5: Check Prime Number

    #include <stdio.h>

    int main()
    {
        int n, i;
        int isPrime = 1;
        printf("Enter a number: ");
        scanf("%d", &n);
        if(n <= 1)
        {
            isPrime = 0;
        }
        else
        {
            for(i = 2; i * i <= n; i++)
            {
                if(n % i == 0)
                {
                    isPrime = 0;
                    break;
                }
            }
        }
        if(isPrime)
            printf("Prime Number");
        else
            printf("Not a Prime Number");
        return 0;
    }

    Program 6: Fibonacci Series

    The Fibonacci sequence begins:

    0 1 1 2 3 5 8 13 21 ...

    C Program

    #include <stdio.h>

    int main()
    {
        int n;
        int a = 0, b = 1, next;
        int i;
        printf("Enter number of terms: ");
        scanf("%d", &n);
        for(i = 1; i <= n; i++)
        {
            printf("%d ", a);
            next = a + b;
            a = b;
            b = next;
        }
        return 0;
    }

    Program 7: Password Retry System

    #include <stdio.h>

    int main()
    {
        int password;
        int attempts = 0;
        while(attempts < 3)
        {
            printf("Enter password: ");
            scanf("%d", &password);
            if(password == 1234)
            {
                printf("Login Successful!");
                break;
            }
            attempts++;
            printf("Incorrect password.\n");
        }
        if(attempts == 3)
        {
            printf("Account temporarily locked.");
        }
        return 0;
    }

    This demonstrates how loops can be used in a simple authentication workflow.


    Common Mistakes When Using Loops

    1. Forgetting to Update the Loop Variable

    Incorrect:

    int i = 1;
    while(i <= 10)
    {
        printf("%d", i);
    }
    This creates an infinite loop.
    Correct:
    int i = 1;
    while(i <= 10)
    {
        printf("%d", i);
        i++;
    }

    2. Using the Wrong Condition

    Incorrect:

    for(i = 1; i >= 10; i++)

    This condition is false immediately.

    Correct:

    for(i = 1; i <= 10; i++)

    3. Off-by-One Errors

    Be careful with:

    i < 10

    and:

    i <= 10

    The first runs from 0 through 9 if starting at 0, while the second includes 10.

    4. Forgetting the Semicolon in do-while

    Correct:

    do
    {
        printf("Hello");
    }
    while(condition);

    The semicolon after while(condition) is required.


    Best Practices for Loops

    Follow these practices when writing loops:

    1. Choose the appropriate loop

    Use for, while, or do-while based on the problem.

    2. Keep the loop condition clear

    Avoid unnecessarily complicated conditions.

    3. Update the loop variable correctly

    Make sure the loop can eventually terminate.

    4. Avoid unnecessary nested loops

    Nested loops can increase execution time significantly.

    5. Use meaningful variable names

    Instead of:

    int x;

    consider:

    int studentCount;

    when appropriate.

    6. Test boundary cases

    Test values such as:

    0
    1

    maximum expected value

    negative values

    for, while and do-while: Quick Revision

    FOR

    Known number of repetitions

    WHILE

    Condition-controlled repetition

    DO-WHILE

    Execute at least once

    Remember:

    for = known iterations

    while = condition first

    do-while = execute first


    Interview Questions on Loops in C

    1. What is a loop in C?

    A loop repeatedly executes a block of statements while a specified condition is satisfied.

    2. How many basic types of loops are available in C?

    There are three:

    • for
    • while
    • do-while

    3. Which loop executes at least once?

    The do-while loop.

    4. What is a nested loop?

    A loop placed inside another loop is called a nested loop.

    5. What does break do?

    It immediately terminates the nearest enclosing loop or switch.

    6. What does continue do?

    It skips the remaining statements of the current iteration and proceeds to the next iteration.

    7. What is an infinite loop?

    A loop that continues indefinitely because its termination condition never becomes false.

    8. Which loop should I use when the number of iterations is known?

    Generally, use a for loop.


    Practice Problems

    Try solving these programs yourself without looking at the solutions.

    Beginner

    1. Print numbers from 1 to 100.
    2. Print numbers from 100 to 1.
    3. Print all even numbers between 1 and 100.
    4. Print all odd numbers between 1 and 100.
    5. Print a multiplication table.
    6. Calculate the sum of numbers from 1 to N.
    7. Calculate the factorial of a number.

    Intermediate

    1. Reverse a number.
    2. Count the digits of a number.
    3. Find the sum of digits.
    4. Check whether a number is palindrome.
    5. Check whether a number is prime.
    6. Print prime numbers between 1 and 100.
    7. Generate the Fibonacci series.
    8. Find the greatest common divisor of two numbers.

    Advanced

    1. Create a menu-driven calculator.
    2. Create an ATM menu using do-while and switch.
    3. Create a password retry system.
    4. Print different star patterns using nested loops.
    5. Create a number guessing game using loops.

    Summary

    In this lesson, you learned one of the most important concepts in C programming: loops.

    You learned how to:

    • Repeat code using for
    • Repeat code using while
    • Guarantee at least one execution with do-while
    • Create nested loops
    • Stop loops using break
    • Skip iterations using continue
    • Understand infinite loops
    • Build practical programs using loops
    • Generate number and star patterns

    Loops are fundamental to programming because they allow us to process large amounts of data and repeat operations efficiently.

    In the next lesson, we'll move to Arrays in C, where you'll learn how to store and process multiple values using a single variable structure.


    Frequently Asked Questions (FAQ)

    What is the easiest loop to learn in C?
    The for loop is often easiest for beginners because initialization, condition, and update are clearly organized in one line.
    What is the difference between while and do-while?
    A while loop checks its condition before executing the body, while a do-while loop checks the condition after executing the body.
    Can a for loop run forever?
    Yes. For example: for(;;) { printf("Infinite Loop"); }
    Can loops be nested in C?
    Yes. A for, while, or do-while loop can be placed inside another loop.
    What is the purpose of break in a loop?
    break immediately exits the nearest enclosing loop.
    What is the purpose of continue?
    continue skips the remaining part of the current iteration and starts the next iteration.
    Which loop is best for menu-driven programs?
    A do-while loop is commonly useful for menu-driven programs because the menu should normally appear at least once.

    0/Post a Comment/Comments

    Thank You For Visit My Website.
    I Will Contact As Soon As Possible.