0
0
Cprogramming~5 mins

Why loops are needed in C

Choose your learning style9 modes available
Introduction

Loops help us repeat actions many times without writing the same code again and again.

When you want to print numbers from 1 to 10.
When you need to add all items in a list.
When you want to keep asking a user for input until they give a correct answer.
When you want to process each item in a collection like an array.
When you want to repeat a task until a condition changes.
Syntax
C
for (initialization; condition; update) {
    // code to repeat
}

while (condition) {
    // code to repeat
}

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

The for loop is good when you know how many times to repeat.

The while loop repeats as long as the condition is true.

Examples
This prints numbers 1 to 5 using a for loop.
C
for (int i = 1; i <= 5; i++) {
    printf("%d\n", i);
}
This prints numbers 1 to 5 using a while loop.
C
int i = 1;
while (i <= 5) {
    printf("%d\n", i);
    i++;
}
This prints numbers 1 to 5 using a do-while loop, which runs the code at least once.
C
int i = 1;
do {
    printf("%d\n", i);
    i++;
} while (i <= 5);
Sample Program

This program counts from 1 to 5 using a for loop and prints each number on a new line.

C
#include <stdio.h>

int main() {
    printf("Counting from 1 to 5 using a for loop:\n");
    for (int i = 1; i <= 5; i++) {
        printf("%d\n", i);
    }
    return 0;
}
OutputSuccess
Important Notes

Loops save time and reduce mistakes by avoiding repeated code.

Always make sure your loop has a condition that will eventually stop it, or it will run forever.

Summary

Loops repeat code to do tasks many times easily.

Use loops when you want to repeat actions without writing the same code again.