Real-Life Examples of If...Else Statements in C
Discover how the if...else
statement in C enables you to manage program flow based on specific conditions. Explore practical examples that illustrate the use of if...else
statements in real-life scenarios.
C If...Else Examples
The if...else
statement in C allows you to control the flow of your program based on certain conditions. Let's explore some real-life examples where if...else
statements can be used.
Example 1: Opening a Door with a Correct Code
In this example, we check if a user enters the correct code to "open" a door.
Example: Door Code Validation
#include <stdio.h>
int main() {
int doorCode = 1337;
if (doorCode == 1337) {
printf("Correct code.\nThe door is now open.\n");
} else {
printf("Wrong code.\nThe door remains closed.\n");
}
return 0;
}
Output:
Output
Correct code.
The door is now open.
Example 2: Check if a Number is Positive or Negative
This example determines whether a given number is positive, negative, or zero.
Example: Positive or Negative Number
#include <stdio.h>
int main() {
int myNum = 10; // Is this a positive or negative number?
if (myNum > 0) {
printf("The value is a positive number.\n");
} else if (myNum < 0) {
printf("The value is a negative number.\n");
} else {
printf("The value is 0.\n");
}
return 0;
}
Output:
Output
The value is a positive number.
Example 3: Check if Someone is Old Enough to Vote
This example checks if a person is old enough to vote based on their age.
Example: Voting Eligibility
#include <stdio.h>
int main() {
int myAge = 25;
int votingAge = 18;
if (myAge >= votingAge) {
printf("Old enough to vote!\n");
} else {
printf("Not old enough to vote.\n");
}
return 0;
}
Output:
Output
Old enough to vote!
Example 4: Check if a Number is Even or Odd
This example checks if a number is even or odd using the modulus operator %
.
Example: Even or Odd Number
#include <stdio.h>
int main() {
int myNum = 5;
if (myNum % 2 == 0) {
printf("%d is even.\n", myNum);
} else {
printf("%d is odd.\n", myNum);
}
return 0;
}
Output:
Output
5 is odd.