Loops in C
Subject: Data Structures and Algorithms · Language: C · Level: beginner · 4 min read
Use for, while, and do while loops to repeat work and solve pattern or counting problems.
A loop is used to repeat a block of code again and again. Without loops, we would have to write the same statement many times, which makes a program long and difficult to maintain.
For example, if you want to print numbers from 1 to 100, you should not write 100 `printf` statements. A loop can do that work in a clean way.
Why Loops Are Important
Loops are used in counting problems, pattern printing, array traversal, searching, sorting, menu-driven programs, and many DSA problems.
Main Parts of a Loop
Most loops have three important parts: initialization, condition, and update.
- Initialization sets the starting value
- Condition decides whether the loop should continue
- Update changes the value after each repetition
Common Loop Patterns
Many loop problems follow common patterns.
- Counting: print numbers from 1 to n
- Accumulation: calculate sum or product
- Filtering: print only even numbers or positive numbers
- Searching: stop when a required value is found
- Repetition until valid input is received
for Loop
A `for` loop is usually used when we know how many times the loop should run.
It keeps the starting value, condition, and update in one line, so it is very useful for counting problems, table printing, array traversal, and pattern programs.
In a `for` loop, initialization runs only once at the beginning. Then C checks the condition. If the condition is true, the loop body runs. After the body, the update part runs, and the condition is checked again.
```c
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}
```
Here, `i` starts from 1. The loop runs while `i <= 5`. After each round, `i++` increases the value by 1.
Read this line like a sentence: start `i` from 1, repeat while `i` is less than or equal to 5, and increase `i` after every repetition.
while Loop
A `while` loop is useful when the number of repetitions depends on a condition.
Use `while` when you cannot clearly say the exact number of repetitions in advance. For example, keep asking for input until the user enters a valid value, or keep reading data until a search value is found.
```c
int i = 1;
while (i <= 5) {
printf("%d ", i);
i++;
}
```
In a `while` loop, the condition is checked before the loop body runs.
If the condition is false in the beginning, the body will not run even once. This is the main difference between `while` and `do while`.
do while Loop
A `do while` loop runs the body at least once, even if the condition is false.
This happens because the condition is checked after the loop body. So first the work happens, then C decides whether to repeat it.
```c
int choice;
do {
printf("Menu shown once");
choice = 0;
} while (choice != 0);
```
This is useful in menu programs where the menu should be shown before asking whether the user wants to continue.
```c
#include <stdio.h>
int main(void) {
int n;
printf("Enter a positive number: ");
scanf("%d", &n);
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
printf("Sum = %d\n", sum);
printf("Numbers printed using while: ");
int i = 1;
while (i <= n) {
printf("%d ", i);
i++;
}
printf("\n");
printf("Countdown using do while: ");
int count = n;
do {
printf("%d ", count);
count--;
} while (count >= 1);
printf("\n");
return 0;
}
```
for vs while vs do while
- Use `for` when the number of repetitions is known
- Use `while` when repetition depends on a condition
- Use `do while` when the loop body must run at least once
Loop Control Statements
- `break` stops the loop immediately
- `continue` skips the current round and moves to the next round
- These are useful in searching, menu programs, and validation problems
Accumulator and Counter
A counter counts how many times something happens. An accumulator stores a running total.
```c
count++;
sum += value;
```
These two patterns appear again and again in arrays, strings, and DSA problems.
Nested Loops
A nested loop means one loop inside another loop. It is commonly used for pattern printing, multiplication tables, matrices, and grid-based problems.
When reading nested loops, understand the outer loop first, then the inner loop. The inner loop usually completes all its rounds for every single round of the outer loop.
Infinite Loop
An infinite loop runs forever because its condition never becomes false.
```c
while (1) {
printf("Running");
}
```
Infinite loops are sometimes used intentionally in menu programs, but they should have a clear `break` condition.
Loops in DSA
Loops are used to traverse arrays, strings, linked lists, stacks, queues, trees, and graphs. If you become comfortable with loops, DSA becomes much easier.
Practice Question
Write a C program that takes a number as input and prints its multiplication table from 1 to 10.