Do While Loop Example in C: A Comprehensive Guide
Introduction
The do-while loop is a type of loop statement in C programming that allows the programmer to execute a block of code repeatedly based on a certain condition. Unlike the "for" loop, which checks the condition before executing the loop, the "do-while" loop executes the loop at least once and then checks the condition. In this article, we will explore the do-while loop example in C, its syntax, and its usage.
Syntax
The syntax for the do-while loop in C is as follows:
do {
statement;
} while (condition);
The code block is executed at least once, and the condition is checked after the code block is executed. If the condition is true, the loop will continue to execute. If the condition is false, the loop will exit.
Example
Let’s consider an example to understand the do-while loop better. We will write a program that prompts the user to enter a number, and then it will add up all the numbers until the user enters 0. The program will continue to run until the user enters 0, and then it will print the total sum.
#include <stdio.h>
int main() {
int sum = 0, num;
do {
printf("Enter a number (-1 to quit): ");
scanf("%d", &num);
sum += num;
} while (num != 0);
printf("The sum is: %dn", sum);
return 0;
}
Break and Continue Statements
The do-while loop can also be controlled using break and continue statements. The break statement can be used to exit the loop, while the continue statement can be used to skip the current iteration and continue with the next one.
Example:
#include <stdio.h>
int main() {
int i;
for (i = 0; i < 5; i++) {
if (i == 3) {
continue; // skip the current iteration
}
printf("The value of i: %dn", i);
}
return 0;
}
In this example, the loop starts from 0 to 4, but when the value of i is 3, the loop skips this iteration and continues with the next one, displaying the values 0, 1, and 4.
Advantages of Do-While Loop
- The
do-whileloop is often used when the number of iterations is not fixed and the programmer wants to execute the loop at least once. - It is also used when the initialization of the loop variable needs to be done before the loop starts.
- The
do-whileloop provides more control over the flow of the program compared to theforloop. - It is more flexible and can be used in situations where the
forloop is not suitable.
Conclusion
In this article, we have covered the concept of the do-while loop in C, its syntax, and its usage. We have also seen an example of a program that demonstrates the use of the do-while loop. The do-while loop is a powerful tool in the C programming language, and it is widely used in various applications. With its ability to execute the loop at least once and its flexibility, the do-while loop is an essential concept for any C programmer to learn.
