Here’s a C code example demonstrating the three primary looping constructs: for
, while
, and do-while
. Each loop here performs a similar task of counting from 1
to 5
, but with a different syntax and approach.
#include <stdio.h> int main() { int i; // Using a for loop to count from 1 to 5 printf("For loop:\n"); for (i = 1; i <= 5; i++) { printf("%d ", i); } printf("\n"); // Using a while loop to count from 1 to 5 printf("While loop:\n"); i = 1; // Initialize i before entering the loop while (i <= 5) { printf("%d ", i); i++; // Increment i at the end of each iteration } printf("\n"); // Using a do-while loop to count from 1 to 5 printf("Do-while loop:\n"); i = 1; // Re-initialize i before entering the loop do { printf("%d ", i); i++; // Increment i at the end of each iteration } while (i <= 5); printf("\n"); return 0; }
Explanation of Looping Constructs
1. For Loop
The for
loop is ideal for a known number of iterations.
Syntax: for (initialization; condition; increment/decrement) { ... }
Example: for (i = 1; i <= 5; i++) { ... }
i = 1
initializes the counter.i <= 5
is the loop condition; it runs as long as this condition is true.i++
incrementsi
at the end of each loop iteration.
Output: The loop prints 1 2 3 4 5 and stops once i exceeds 5.
2. While Loop
The while
loop is used when the number of iterations is not known in advance but depends on a condition.
Syntax: while (condition) { ... }
Example: while (i <= 5) { ... }
i = 1
initializes the counter before the loop.i <= 5
is checked before each iteration, so the loop runs as long as this is true.i++
incrementsi
at the end of each iteration.
Output: This loop also prints 1 2 3 4 5
and stops once i
exceeds 5
.
3. Do-While Loop
The do-while
loop is similar to while
but guarantees at least one iteration since the condition is evaluated after each loop.
Syntax: do { ... } while (condition);
Example: do { ... } while (i <= 5);
i = 1
initializes the counter before the loop.- The code inside the
{ ... }
block executes at least once. i <= 5
is checked after each iteration, so the loop continues if the condition remains true.
Output: This loop also prints 1 2 3 4 5
and stops once i exceeds 5
.
Summary of Looping Constructs
for
loop: Ideal when the number of iterations is fixed or known.while
loop: Preferred when the loop depends on a condition that might vary dynamically, such as user input or program state.do-while
loop: Guarantees at least one iteration, useful when you need the loop to run before checking the condition.
Each loop structure gives flexibility in controlling how many times a block of code executes, based on different types of conditions and requirements.