Real-Life Examples of While Loops in C
Discover practical applications of while loops in C programming through real-life examples. This section includes a simple countdown program that demonstrates how while loops can be effectively utilized in various scenarios.
C While Loop Examples
Real-Life Examples
To illustrate a practical use of the while loop, we’ve created a simple countdown program:
Example
int countdown = 4;
while (countdown > 0) {
printf("%d\n", countdown);
countdown--;
}
printf("Happy Anniversary!!\n");
In this next example, we create a program that prints only the even numbers from 0 to 20 (inclusive):
Example
int i = 0;
while (i <= 20) {
printf("%d\n", i);
i += 2;
}
Next, we’ll use a while loop to reverse a set of digits:
Example
// A variable containing specific digits
int numbers = 67890;
// A variable to hold the reversed number
int revNumbers = 0;
// Reverse the order of the digits
while (numbers) {
// Extract the last digit from 'numbers' and add it to 'revNumbers'
revNumbers = revNumbers * 10 + numbers % 10;
// Remove the last digit from 'numbers'
numbers /= 10;
}
Lastly, here’s a fun example of using a while loop in a Yatzy game:
Example
int dice = 1;
while (dice <= 6) {
if (dice < 6) {
printf("No Yatzy\n");
} else {
printf("Yipee!\n");
}
dice++;
}
If the loop encounters values from 1 to 5, it outputs "No Yatzy". When it hits the value 6, it displays "Yipee!".