Nano Technology

Looping Statements in C


1. What are Loops?

Loops in C are control structures that allow a set of statements to be executed repeatedly as long as a given condition is true. Instead of writing the same code multiple times, loops help reduce redundancy and make programs efficient and readable.

Loops are widely used for processing arrays, performing repetitive calculations, and controlling program flow.

2. while Loop

The while loop is an entry-controlled loop. The condition is checked before executing the loop body. If the condition is false initially, the loop body will not execute even once.


while (condition)
{
    // statements
}

The while loop is suitable when the number of iterations is not known in advance.

3. do–while Loop

The do–while loop is an exit-controlled loop. The loop body is executed first, and the condition is checked after execution. Therefore, the loop executes at least once.


do
{
    // statements
}
while (condition);
                    

The semicolon at the end of the while condition is mandatory.

4. 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 line.


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

The for loop is commonly used for array traversal and counter-based repetitions.

5. Nested Loops

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


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

Nested loops are commonly used in matrix operations and pattern printing programs.

6. break and continue

The break statement is used to terminate a loop immediately and transfer control to the statement following the loop.


if (i == 5)
    break;

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


if (i == 5)
    continue;

7. Infinite Loops

An infinite loop is a loop that never terminates because the condition always remains true.


while (1)
{
    // infinite loop
}

Infinite loops are used in embedded systems and real-time applications, but they should be handled carefully to avoid program hanging.

8. Loop Examples


#include <stdio.h>

int main()
{
    int i;

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

    return 0;
}

This program uses a for loop to print numbers from 1 to 5.

9. Common Errors

  • Missing initialization or increment/decrement
  • Using incorrect loop condition
  • Forgetting semicolon in do–while loop
  • Creating unintended infinite loops
  • Incorrect placement of break and continue
Note: A strong understanding of looping statements is essential before learning arrays, strings, and complex algorithms.