While Loop Real-Life Examples
Real-Life Examples
While loops are used in programming to repeat a set of instructions as long as a certain condition is true. In real-life scenarios, this concept can be likened to situations where you perform a task repeatedly until a specific condition is met. Here are some real-life examples that illustrate the concept of a while loop:
Example
#include <stdio.h>
int main() {
int countdown = 3;
while (countdown > 0) {
printf("%d\n", countdown);
countdown--;
}
printf("Happy New Year!!\n");
return 0;
}
Output
3
2
1
Happy New Year!!
Using Yatzy game as a practical example for a while loop and if-else statement combination is engaging and relatable.
Example
Print "Yatzy!" If the dice number is 6:#include <stdio.h>
int main() {
int dice = 1;
while (dice <= 6) {
if (dice < 6) {
printf("No Yatzy\n");
} else {
printf("Yatzy!\n");
}
dice = dice + 1;
}
return 0;
}
Output
No Yatzy
No Yatzy
No Yatzy
No Yatzy
No Yatzy
Yatzy!