C (programming language)
C Program to Print Numbers Till 5 using do-while Loop
Understanding the do-while Loop
- Exit-controlled loop: The do-while loop first executes the code block within the loop, and then checks the condition.
- Guaranteed execution: This means the code block will always execute at least once, even if the condition is initially false.
Code Structure and Explanation
C
#include <stdio.h>
int main() {
int i = 1; // Initialize the counter variable
do {
printf("%d ", i); // Print the current value of i
i++; // Increment the counter for the next iteration
} while (i <= 5); // Check the condition (loop continues if i is less than or equal to 5)
return 0;
}
Explanation:
- Header Inclusion:
#include <stdio.h>
provides input/output functions likeprintf
. - Main Function: The program execution begins in the
main
function. - Variable Declaration:
int i = 1;
declares and initializes the counter variablei
to 1. - do-while Loop:
- The
do
block executes first, printing the current value ofi
and then incrementing it. - The
while
conditioni <= 5
checks ifi
is still within the range (less than or equal to 5). - If the condition is true, the loop repeats, printing the next number.
- The
- Loop Termination: The loop continues as long as
i
is less than or equal to 5. Oncei
becomes 6, the condition becomes false and the loop terminates. - Return Statement:
return 0;
indicates successful program termination.
Output:
1 2 3 4 5
Key Points:
- The do-while loop is useful when you need the code block to execute at least once, regardless of the condition.
- The condition is checked at the end of the loop, ensuring at least one iteration.
- Other loop types like
for
andwhile
may be more suitable in different scenarios, depending on the specific requirements.