C If-Else Real-Life Examples
Practical Applications of If-Else Statements
If-else statements are fundamental to programming and are used in virtually every real-world application. They enable programs to make decisions, validate input, handle errors, and respond to different conditions.
This section explores practical examples of how if-else statements are used in real programming scenarios.
User Authentication System
One of the most common uses of if-else statements is in user authentication systems to verify credentials and grant appropriate access.
#include <stdio.h>
#include <string.h>
int main(void) {
const char username[] = "admin";
const char password[] = "secret123";
char inputUser[20], inputPass[20];
printf("Enter username: ");
scanf("%19s", inputUser); // width-limited to avoid overflow
printf("Enter password: ");
scanf("%19s", inputPass); // width-limited to avoid overflow
if (strcmp(inputUser, username) == 0 && strcmp(inputPass, password) == 0) {
printf("Login successful! Welcome, %s.\n", inputUser);
} else {
printf("Invalid username or password. Access denied.\n");
}
return 0;
}
Enter username: admin Enter password: secret123 Login successful! Welcome, admin.
Grading System
If-else if ladders are perfect for implementing grading systems where scores map to specific letter grades.
#include <stdio.h>
int main(void) {
int score;
printf("Enter your score (0-100): ");
if (scanf("%d", &score) != 1) {
printf("Invalid input!\n");
return 1;
}
if (score < 0 || score > 100) {
printf("Invalid score! Please enter a value between 0 and 100.\n");
} else if (score >= 90) {
printf("Grade: A\n");
} else if (score >= 80) {
printf("Grade: B\n");
} else if (score >= 70) {
printf("Grade: C\n");
} else if (score >= 60) {
printf("Grade: D\n");
} else {
printf("Grade: F\n");
}
return 0;
}
Enter your score (0-100): 85 Grade: B
E-commerce Discount Calculation
E-commerce systems use if-else statements to apply different discount levels based on purchase amount or customer status.
#include <stdio.h>
int main(void) {
double totalAmount;
char isMember;
printf("Enter total purchase amount: $");
if (scanf("%lf", &totalAmount) != 1) {
printf("Invalid amount.\n");
return 1;
}
if (totalAmount < 0.0) {
printf("Amount cannot be negative.\n");
return 1;
}
printf("Are you a member? (y/n): ");
scanf(" %c", &isMember); // leading space eats leftover newline
double discount = 0.0;
if (isMember == 'y' || isMember == 'Y') {
if (totalAmount > 200.0) {
discount = 0.20;
} else if (totalAmount > 100.0) {
discount = 0.15;
} else if (totalAmount > 50.0) {
discount = 0.10;
} else {
discount = 0.05;
}
} else {
if (totalAmount > 200.0) {
discount = 0.10;
} else if (totalAmount > 100.0) {
discount = 0.05;
}
}
double finalAmount = totalAmount * (1.0 - discount);
printf("Discount: %.0f%%, Final amount: $%.2f\n", discount * 100.0, finalAmount);
return 0;
}
Enter total purchase amount: $150 Are you a member? (y/n): y Discount: 15%, Final amount: $127.50
Temperature Monitoring System
Embedded systems often use if-else statements to monitor sensors and trigger actions based on thresholds.
#include <stdio.h>
int main(void) {
double temperature;
printf("Enter current temperature in Celsius: ");
if (scanf("%lf", &temperature) != 1) {
printf("Invalid input.\n");
return 1;
}
if (temperature > 40.0) {
printf("CRITICAL: Temperature too high! Activating emergency cooling.\n");
} else if (temperature > 35.0) {
printf("WARNING: Temperature approaching critical level. Increasing fan speed.\n");
} else if (temperature > 30.0) {
printf("Notice: Temperature is elevated. Monitoring closely.\n");
} else if (temperature > 20.0) {
printf("Normal operating temperature.\n");
} else if (temperature > 10.0) {
printf("Notice: Temperature is low. Reducing fan speed.\n");
} else if (temperature > 0.0) {
printf("WARNING: Temperature approaching minimum operating level.\n");
} else {
printf("CRITICAL: Temperature below freezing! System may shut down.\n");
}
return 0;
}
Enter current temperature in Celsius: 37 WARNING: Temperature approaching critical level. Increasing fan speed.
Game Development Logic
Games use if-else statements extensively for game logic, such as checking win conditions, player status, and interactions.
#include <stdio.h>
int main(void) {
int playerHealth = 75;
int hasKey = 1;
int enemiesDefeated = 3;
printf("Game Status Check:\n");
if (playerHealth <= 0) {
printf("Game Over! You have been defeated.\n");
} else if (playerHealth < 20) {
printf("Warning: Health critically low! Find healing.\n");
} else if (playerHealth < 50) {
printf("Caution: Health is low. Proceed carefully.\n");
} else {
printf("Health status: Good.\n");
}
if (hasKey && enemiesDefeated >= 5) {
printf("You can now enter the final chamber!\n");
} else if (hasKey) {
int remaining = 5 - enemiesDefeated;
if (remaining < 0) remaining = 0;
printf("You have the key, but need to defeat %d more enemies.\n", remaining);
} else if (enemiesDefeated >= 5) {
printf("You've defeated enough enemies, but need to find the key.\n");
} else {
printf("Continue exploring. Defeat enemies and find the key.\n");
}
return 0;
}
Game Status Check: Health status: Good. You have the key, but need to defeat 2 more enemies.
Best Practices in Real-World Code
1. Always validate input before using it in conditions (check scanf return values).
2. Use meaningful variable names that reflect their purpose.
3. Keep conditions simple and consider breaking complex ones into separate variables.
4. Use comments to explain why certain conditions are important.
5. Consider using switch statements for multiple exclusive conditions on the same variable.
6. Handle edge cases and unexpected inputs with else clauses.
7. When reading strings with scanf, use width limits (e.g., %19s) to prevent buffer overflow.