SrcForge

Lesson 11

Looping Statements

Looping statements, also known as iteration statements, allow a block of code to execute repeatedly until a specified condition becomes false. C provides three types of looping statements: for, while, and do...while.

C Track

Save progress as you learn.

44 lessons

Lesson content

Looping Statements in C Programming

In programming, there are many situations where a set of statements needs to be executed repeatedly. Writing the same code multiple times not only increases the program size but also makes it difficult to maintain. Looping statements solve this problem by allowing a block of code to execute repeatedly until a specified condition becomes false.

Looping statements, also known as iteration statements, are one of the most important control structures in C programming. They help automate repetitive tasks, making programs shorter, more efficient, and easier to understand.

For example, loops are commonly used to:

  • Print numbers from 1 to 100.
  • Calculate the sum of a series of numbers.
  • Display multiplication tables.
  • Process arrays and strings.
  • Repeat menu-driven programs until the user chooses to exit.

Prerequisites

  • Introduction to C Programming
  • Variables and Constants
  • Data Types
  • Operators and Expressions
  • Control Structures
  • Decision-Making Statements (if, if...else, switch)

Core Concepts: Looping Statements in C

A loop is a control structure that repeatedly executes a block of code as long as a specified condition is true. Instead of writing the same statements multiple times, programmers use loops to perform repetitive tasks efficiently.

C programming provides three types of looping statements:

  1. for Loop
  2. while Loop
  3. do...while Loop

Types of Loops in C

LoopCondition CheckMinimum Executions
forBefore execution0
whileBefore execution0
do...whileAfter execution1

1. for Loop

The for loop is used when the number of iterations is known in advance. It combines initialization, condition checking, and increment/decrement in a single statement.

Syntax

for(initialization; condition; increment/decrement)
{
    // Statements
}

Flow of Execution

  1. Initialize the loop variable.
  2. Check the condition.
  3. Execute the loop body if the condition is true.
  4. Update the loop variable.
  5. Repeat until the condition becomes false.

Example 1: Print Numbers from 1 to 5

#include <stdio.h>                    // Includes standard input/output library

int main()                            // Main function
{
    int i;                            // Declares loop variable

    for(i = 1; i <= 5; i++)           // Initializes, checks condition, and increments
    {
        printf("%d\n", i);            // Prints the value of i
    }

    return 0;                         // Ends the program
}

Output: 1 2 3 4 5

2. while Loop

The while loop executes a block of code as long as the specified condition remains true. It is generally used when the number of iterations is not known beforehand.

Syntax

while(condition)
{
    // Statements
}

Flow of Execution

  1. Evaluate the condition.
  2. If the condition is true, execute the loop body.
  3. Update the loop variable.
  4. Repeat until the condition becomes false.

Example 2: Print Numbers from 1 to 5

#include <stdio.h>                    // Includes standard input/output library

int main()                            // Main function
{
    int i = 1;                        // Initializes loop variable

    while(i <= 5)                     // Checks the condition
    {
        printf("%d\n", i);            // Prints the current value

        i++;                          // Increments the loop variable
    }

    return 0;                         // Ends the program
}

Output: 1 2 3 4 5

3. do...while Loop

The do...while loop is similar to the while loop, except that the condition is checked after executing the loop body. Therefore, the statements inside the loop execute at least once.

Syntax

do
{
    // Statements
}
while(condition);

Flow of Execution

  1. Execute the loop body.
  2. Check the condition.
  3. If true, repeat the loop.
  4. Otherwise, terminate the loop.

Example 3: Print Numbers from 1 to 5

#include <stdio.h>                    // Includes standard input/output library

int main()                            // Main function
{
    int i = 1;                        // Initializes loop variable

    do                                // Starts the do-while loop
    {
        printf("%d\n", i);            // Prints the current value

        i++;                          // Increments the loop variable

    } while(i <= 5);                  // Checks the condition

    return 0;                         // Ends the program
}

Output: 1 2 3 4 5

Nested Loops

A nested loop is a loop placed inside another loop. The inner loop executes completely for every iteration of the outer loop.

Example

#include <stdio.h>                        // Includes standard input/output library

int main()                                // Main function
{
    int i, j;                             // Declares loop variables

    for(i = 1; i <= 3; i++)               // Outer loop
    {
        for(j = 1; j <= 2; j++)           // Inner loop
        {
            printf("(%d,%d) ", i, j);     // Prints the pair
        }

        printf("\n");                     // Moves to the next line
    }

    return 0;                             // Ends the program
}

Output: (1,1) (1,2) / (2,1) (2,2) / (3,1) (3,2)

Loop Control Statements

Loop control statements modify the normal execution of a loop.

StatementPurpose
breakTerminates the loop immediately.
continueSkips the remaining statements of the current iteration and moves to the next iteration.

Example using break

for(int i = 1; i <= 10; i++)
{
    if(i == 6)
        break;

    printf("%d ", i);
}

Output: 1 2 3 4 5

Example using continue

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

    printf("%d ", i);
}

Output: 1 2 4 5

Comparison of Looping Statements

Featurefor Loopwhile Loopdo...while Loop
Condition CheckBefore executionBefore executionAfter execution
Executes at Least OnceNoNoYes
Best Used WhenNumber of iterations is knownNumber of iterations is unknownLoop must execute at least once
InitializationInside loopOutside loopOutside loop
Update StatementInside loopInside loop bodyInside loop body

Common Mistakes and Pitfalls

Incorrect CodeCorrect CodeReason
for(i=1; i<=5;)for(i=1; i<=5; i++)Missing update expression can create an infinite loop.
while(i<=5);while(i<=5)Avoid placing a semicolon immediately after the loop condition.
Forgetting to update the loop variableIncrement or decrement the loop variableThe loop may never terminate.
Using = instead of == in conditionsUse == for comparisonAssignment changes the variable instead of comparing values.

Best Practices

  • Choose the appropriate loop based on the problem.
  • Use meaningful loop variable names when necessary.
  • Always ensure that the loop condition eventually becomes false.
  • Avoid unnecessary nested loops to improve performance.
  • Use break and continue only when they improve readability.
  • Keep loop bodies simple and easy to understand.

When NOT to Use Looping Statements

Avoid using loops when:

  • The task needs to be performed only once.
  • A recursive solution is more appropriate for the problem.
  • An infinite loop is not intentionally required.
  • Repeated execution can be replaced with library functions for better efficiency.

Summary / Key Takeaways

  • A loop repeatedly executes a block of code until a condition becomes false.
  • C provides three looping statements: for, while, and do...while.
  • The for loop is suitable when the number of iterations is known.
  • The while loop is used when the number of iterations is unknown.
  • The do...while loop guarantees at least one execution.
  • Nested loops allow one loop to execute inside another.
  • break terminates a loop, while continue skips the current iteration.
  • Proper use of loops reduces code duplication and improves program efficiency.

FAQ About Looping Statements in C

1. What is a looping statement in C programming?

A looping statement repeatedly executes a block of code until a specified condition becomes false. It helps automate repetitive tasks and reduces code duplication.

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

C provides three types of loops: for loop, while loop, and do...while loop.

3. What is the difference between while and do...while loops?

The while loop checks the condition before executing the loop body, whereas the do...while loop checks the condition after executing the loop body, ensuring that the loop executes at least once.

4. When should I use a for loop?

Use a for loop when the number of iterations is known in advance, such as printing numbers from 1 to 100 or traversing an array.

5. What is an infinite loop?

An infinite loop is a loop whose condition never becomes false, causing it to execute indefinitely. This usually happens when the loop variable is not updated correctly.

6. What is the purpose of break and continue in loops?

break immediately exits the loop. continue skips the remaining statements of the current iteration and proceeds to the next iteration.