Introduction to the Do-While Loop
In the C programming language, the do-while loop is a control flow statement that allows a block of code to be executed repeatedly until a specified condition is no longer true. Unlike the while loop, the do-while loop guarantees that the code block will be executed at least once, as the condition is checked after the execution of the block.
Syntax of the Do-While Loop
The syntax of the do-while loop in C is as follows:
do { // Code block to be executed } while (condition);
The code block is enclosed within the curly braces, and the condition is checked at the end of each iteration. If the condition evaluates to true, the code block is executed again. If the condition evaluates to false, the loop terminates, and the program continues with the next line of code after the loop.
Example 1: Printing Numbers using the Do-While Loop
Let’s start with a simple example to demonstrate the usage of the do-while loop. In this example, we will print the numbers from 1 to 5:
#include int main() { int i = 1; do { printf("%d ", i); i++; } while (i <= 5); return 0; }
Output:
1 2 3 4 5
In this example, the variable i
is initialized to 1. The code block inside the do-while loop is executed, which prints the value of i
and increments it by 1. The loop continues until i
becomes greater than 5.
Example 2: Calculating the Sum of Numbers
Let’s explore a more practical example using the do-while loop. In this example, we will calculate the sum of numbers entered by the user until a negative number is encountered:
#include int main() { int num, sum = 0; do { printf("Enter a number (enter a negative number to stop): "); scanf("%d", #); if (num >= 0) { sum += num; } } while (num >= 0); printf("The sum of the entered numbers is %d", sum); return 0; }
Output:
Enter a number (enter a negative number to stop): 5 Enter a number (enter a negative number to stop): 3 Enter a number (enter a negative number to stop): -2 The sum of the entered numbers is 8
In this example, the user is prompted to enter a number. If the number is non-negative, it is added to the sum
variable. The loop continues until a negative number is entered, at which point the loop terminates, and the sum is displayed.
The do-while loop in C is a powerful control flow statement that allows for the repeated execution of a code block until a specified condition is no longer true. It is particularly useful when you want to ensure that the code block is executed at least once. By understanding the syntax and examples provided in this article, you should now have a solid understanding of how to use the do-while loop in your C programs.