Loops in C Language
Introduction
Loops are fundamental control structures in programming that allow you to execute a block of code multiple times. In the C programming language, there are three main types of loops:
- While Loop
- Do-While Loop
- For Loop
While Loop
The while loop continues to execute a block of code as long as a specified condition is true.
Syntax
// code block to be executed
}
Example
while (i < 5) {
printf("%d\n", i);
i++;
}
1
2
3
4
Do-While Loop
The do-while loop is similar to the while loop, but it guarantees that the code block will be executed at least once.
Syntax
// code block to be executed
} while (condition);
Example
do {
printf("%d\n", i);
i++;
} while (i < 5);
1
2
3
4
For Loop
The for loop is a more compact form of loop that combines initialization, condition-checking, and increment/decrement in a single line.
Syntax
// code block to be executed
}
Example
printf("%d\n", i);
}
1
2
3
4
Nested Loops
Loops can be nested within other loops. This is useful for iterating over multi-dimensional arrays or performing complex iterations.
Example
for (int j = 0; j < 3; j++) {
printf("i = %d, j = %d\n", i, j);
}
}
i = 0, j = 1
i = 0, j = 2
i = 1, j = 0
i = 1, j = 1
i = 1, j = 2
i = 2, j = 0
i = 2, j = 1
i = 2, j = 2
Conclusion
Understanding loops allows you to write more efficient and powerful programs. Whether you need to perform repetitive tasks or iterate over data structures, loops are an essential tool in your programming arsenal.