Paramclasses Academy - Blog

Tutorials Details

←
Post 9 of 15
→

What is Loops in C programming ?

What is Loops in C programming ?

October 14, 2026

1. Introduction

In Module 4, we learned how to use conditional statements such as if, if-else, and switch to make decisions in C programming.

Now, we will learn about loops, which allow us to execute a block of code repeatedly without writing the same statements again and again.

For example, suppose you want to print the numbers from 1 to 100. Writing 100 separate printf() statements would be inefficient. A loop allows you to accomplish this with just a few lines of code.

Loops are commonly used for:

  • Printing number sequences.

  • Calculating sums and averages.

  • Processing arrays.

  • Repeating menu operations.

  • Validating user input.

  • Building mathematical and data-processing programs.

By the end of this module, you will understand the for, while, and do-while loops, along with break and continue.

2. What Is a Loop?

A loop is a programming structure that repeatedly executes a block of statements while a specified condition permits it.

A loop generally involves three elements:

  1. Initialization: Establishes the starting value of a loop variable.

  2. Condition: Determines whether the loop should continue.

  3. Update: Changes the loop variable so that the loop can eventually terminate.

Not every loop uses all three elements explicitly, but they are common in introductory examples.

C provides three main looping statements:

  • for loop

  • while loop

  • do-while loop

3. The for Loop

The for loop is commonly used when the number of iterations is known or controlled by a counter.

Syntax

for (initialization; condition; update)
{
    // Statements to repeat
}

Example 1: Print Numbers from 1 to 5

#include <stdio.h>

int main(void)
{
    int i;

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

    return 0;
}

Output:

1
2
3
4
5

Explanation

  • i = 1 initializes the loop variable.

  • i <= 5 checks whether the loop should continue.

  • i++ increments i after each iteration.

  • printf() displays the current value.

The loop stops when i becomes 6, because the condition i <= 5 is then false.

Execution table

Iteration

Value of i

Condition

Action

1

1

True

Print 1

2

2

True

Print 2

3

3

True

Print 3

4

4

True

Print 4

5

5

True

Print 5

6

6

False

Stop

4. Calculating the Sum of Numbers Using a for Loop

Loops are useful for performing repetitive calculations.

Example 2: Sum of Numbers from 1 to 10

#include <stdio.h>

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

    for (i = 1; i <= 10; i++)
    {
        sum += i;
    }

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

    return 0;
}

Output:

Sum = 55

Explanation

The variable sum begins at zero.

During each iteration, the current value of i is added to sum.

The calculation is:

\[ 1+2+3+\cdots+10=55 \]

This approach is useful when accumulating totals, calculating averages, and processing a sequence of values.

5. The while Loop

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

It is especially useful when the number of iterations is not known in advance.

Syntax

while (condition)
{
    // Statements to repeat
}

Example 3: Print Numbers from 1 to 5

#include <stdio.h>

int main(void)
{
    int i = 1;

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

    return 0;
}

Output:

1
2
3
4
5

Explanation

  1. The variable i starts at 1.

  2. The condition i <= 5 is checked before each iteration.

  3. The current value of i is printed.

  4. i++ increases the value by one.

  5. The loop terminates when the condition becomes false.

Important: If you forget to update i, the condition may remain true indefinitely, creating an infinite loop.

6. The do-while Loop

The do-while loop executes its body first and checks the condition afterward.

Therefore, the loop body always executes at least once.

Syntax

do
{
    // Statements to repeat
}
while (condition);

Notice the semicolon after the while condition.

Example 4: Print Numbers from 1 to 5

#include <stdio.h>

int main(void)
{
    int i = 1;

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

    return 0;
}

Output:

1
2
3
4
5

Example 5: Demonstrating One Guaranteed Iteration

#include <stdio.h>

int main(void)
{
    int i = 10;

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

    return 0;
}

Output:

Value: 10

Even though the condition is false after the first iteration, the body executes once before the condition is checked.

7. Difference Between for, while, and do-while

Feature

for

while

do-while

Condition checked

Before each iteration

Before each iteration

After each iteration

Minimum iterations

Zero

Zero

One

Typical use

Counter-controlled repetition

Condition-controlled repetition

Actions that must happen at least once

Update location

Usually in the loop header

Usually inside the body

Usually inside the body

All three loops can often be used to solve the same problem. Choose the one that makes your program easiest to understand.

8. The break Statement

The break statement immediately terminates the innermost enclosing loop.

It is useful when you need to stop searching or terminate a loop after a particular event.

Example 6: Stop When the Counter Reaches 5

#include <stdio.h>

int main(void)
{
    int i;

    for (i = 1; i <= 10; i++)
    {
        if (i == 5)
        {
            break;
        }

        printf("%d\n", i);
    }

    return 0;
}

Output:

1
2
3
4

When i becomes 5, the break statement terminates the loop before printf() executes for that iteration.

9. The continue Statement

The continue statement skips the remaining statements in the current iteration and proceeds to the next iteration of the loop.

Example 7: Skip the Number 3

#include <stdio.h>

int main(void)
{
    int i;

    for (i = 1; i <= 5; i++)
    {
        if (i == 3)
        {
            continue;
        }

        printf("%d\n", i);
    }

    return 0;
}

Output:

1
2
4
5

When i equals 3, continue skips the printf() statement for that iteration.

Important: In a for loop, continue proceeds to the update expression before checking the condition again. In a while loop, it returns to the condition check, so ensure your update logic cannot be skipped in a way that creates an infinite loop.

10. Nested Loops

A nested loop is a loop placed inside another loop.

Nested loops are useful for working with patterns, tables, matrices, and two-dimensional arrays.

Example 8: Print a Star Pattern

#include <stdio.h>

int main(void)
{
    int i, j;

    for (i = 1; i <= 4; i++)
    {
        for (j = 1; j <= i; j++)
        {
            printf("*");
        }

        printf("\n");
    }

    return 0;
}

Output:

*
**
***
****

Explanation

  • The outer loop controls the number of rows.

  • The inner loop controls the number of stars in each row.

  • printf("\n") moves the output to the next line after each row.

On the first row, one star is printed. On the second row, two stars are printed, and so on.

11. Multiplication Table Using a Loop

Let's create a program that prints the multiplication table for a number entered by the user.

#include <stdio.h>

int main(void)
{
    int number;
    int i;

    printf("Enter a number: ");

    if (scanf("%d", &number) != 1)
    {
        printf("Invalid input.\n");
        return 1;
    }

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

    return 0;
}

Sample input:

Enter a number: 5

Output:

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

This program demonstrates how a loop can replace repetitive statements with a concise and maintainable solution.

12. Real-World Example: Password Attempt Counter

Loops can repeat an action until a condition is met. The following example demonstrates a limited number of attempts for a simple practice program.

#include <stdio.h>

int main(void)
{
    int attempts = 0;
    int answer;

    while (attempts < 3)
    {
        printf("Enter the number 7: ");

        if (scanf("%d", &answer) != 1)
        {
            printf("Invalid input.\n");
            return 1;
        }

        if (answer == 7)
        {
            printf("Correct answer!\n");
            break;
        }

        attempts++;
        printf("Incorrect answer.\n");
    }

    if (attempts == 3)
    {
        printf("Maximum attempts reached.\n");
    }

    return 0;
}

This is a basic exercise in loop control, not a secure password system.

In production applications, authentication requires proper credential verification, secure storage, and appropriate rate limiting.

13. Common Beginner Mistakes

  1. Forgetting to initialize the loop variable.

  2. Forgetting to update the loop variable.

  3. Using the wrong condition, causing an extra or missing iteration.

  4. Accidentally creating an infinite loop.

  5. Forgetting the semicolon after the while condition in a do-while loop.

  6. Using break when you only intended to skip one iteration.

  7. Using continue in a while loop before updating the counter.

  8. Confusing the inner and outer loop variables in nested loops.

  9. Using a loop counter type or range that cannot represent the intended values.

14. Practical Exercises

Write C programs to complete these exercises:

  1. Print numbers from 1 to 100 using a for loop.

  2. Print all even numbers between 1 and 50.

  3. Calculate the sum of numbers from 1 to n.

  4. Print the multiplication table of a user-entered number.

  5. Calculate the factorial of a nonnegative integer.

  6. Reverse the digits of an integer.

  7. Count the digits in an integer.

  8. Print a star triangle using nested loops.

  9. Display numbers from 1 to 20, skipping multiples of 3.

  10. Create a menu-driven program that repeats until the user selects Exit.

15. Interview Questions

Q1. What is a loop in C?

A loop repeatedly executes a block of statements while its continuation condition permits it.

Q2. How many main looping statements does C provide?

C provides three main looping statements: for, while, and do-while.

Q3. What is the difference between while and do-while?

A while loop checks its condition before executing the body. A do-while loop checks the condition afterward.

Q4. What is an infinite loop?

A loop that does not terminate under its current execution conditions.

Q5. What does break do?

It immediately exits the innermost enclosing loop or switch statement.

Q6. What does continue do?

It skips the remainder of the current iteration and proceeds to the next iteration.

Q7. What is a nested loop?

A loop placed inside another loop.

Q8. When should you use a for loop?

A for loop is often convenient when repetition is controlled by a counter or a known range.

16. Quick Revision

  • Loops execute statements repeatedly.

  • for loops are commonly used for counter-controlled repetition.

  • while loops check the condition before each iteration.

  • do-while loops execute at least once.

  • break terminates the innermost enclosing loop.

  • continue skips the remainder of the current iteration.

  • Nested loops help generate patterns and process multidimensional data.

  • Proper initialization, conditions, and updates help prevent infinite loops.

17. Homework

Create a Number Analysis Program with the following requirements:

  1. Ask the user to enter a positive integer.

  2. Validate the input.

  3. Print all numbers from 1 to the entered number.

  4. Calculate the sum of those numbers.

  5. Count how many numbers in the range are even.

  6. Display the multiplication table of the entered number from 1 to 10.

  7. Use at least one for loop and one while loop.

  8. Ensure that the program handles invalid input and avoids unnecessary infinite loops.

Expected output format

For an input of 5, part of the output should look like this:

Enter a positive integer: 5

Numbers: 1 2 3 4 5
Sum: 15
Even numbers count: 2

Multiplication Table:
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
...
5 x 10 = 50

Conclusion

In Module 5, you learned how to use for, while, and do-while loops to repeat operations. You also learned how break and continue control loop execution and how nested loops can generate patterns and tables.

←
Post 9 of 15
→