C Lesson 11 – Loops | Dataplexa

Loops in C

So far, our programs execute statements only once. But in real programming, we often need to repeat a block of code multiple times.

Loops allow us to execute a set of statements repeatedly based on a condition.


Why Loops Are Needed

Imagine you want to print numbers from 1 to 100. Without loops, you would need 100 print statements.

Loops solve this problem efficiently and cleanly.


Types of Loops in C

C provides three main looping statements:

  • while loop
  • for loop
  • do-while loop

1. while Loop

The while loop checks the condition first. If the condition is true, the loop body executes.

Syntax:


while (condition) {
    // statements
}

Example: Print Numbers from 1 to 5


#include <stdio.h>

int main() {
    int i = 1;

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

    return 0;
}

Here:

  • The condition is checked before each iteration
  • The loop stops when the condition becomes false

2. for Loop

The for loop is used when the number of iterations is known in advance.

Syntax:


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

Example: Print Even Numbers from 2 to 10


#include <stdio.h>

int main() {
    int i;

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

    return 0;
}

The for loop keeps everything (initialization, condition, update) in one place, making it easy to read.


3. do-while Loop

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

Syntax:


do {
    // statements
} while (condition);

Example: Print Number Once Even If Condition Is False


#include <stdio.h>

int main() {
    int i = 10;

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

    return 0;
}

This loop prints the value once because the condition is checked after execution.


Choosing the Right Loop

  • Use while when condition is primary
  • Use for when count is known
  • Use do-while when at least one execution is required

Mini Practice

  • Print numbers from 10 to 1 using a loop
  • Print multiplication table of a number
  • Find sum of first 10 natural numbers

Quick Quiz

Q1. Which loop checks condition first?

while loop

Q2. Which loop executes at least once?

do-while loop

Q3. Which loop is best when number of iterations is known?

for loop

Q4. Can while loop execute zero times?

Yes, if the condition is false initially

Q5. What happens if loop condition never becomes false?

It results in an infinite loop