c
examples
examples.c🔧c
/**
* @file examples.c
* @brief if, else, and else if Statement Examples
*
* This file demonstrates decision-making statements in C.
*
* Compile: gcc -Wall examples.c -o examples
* Run: ./examples
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* ============================================================
* EXAMPLE 1: BASIC IF STATEMENT
* ============================================================ */
void example_basic_if() {
printf("\n=== Example 1: Basic if Statement ===\n");
int temperature = 30;
// Simple if statement
if (temperature > 25) {
printf("It's a hot day!\n");
}
// Another example
int age = 20;
if (age >= 18) {
printf("You are an adult.\n");
}
// Checking a condition
int number = 42;
if (number % 2 == 0) {
printf("%d is an even number.\n", number);
}
}
/* ============================================================
* EXAMPLE 2: IF-ELSE STATEMENT
* ============================================================ */
void example_if_else() {
printf("\n=== Example 2: if-else Statement ===\n");
int number = 7;
// Check odd or even
if (number % 2 == 0) {
printf("%d is even.\n", number);
} else {
printf("%d is odd.\n", number);
}
// Check positive or negative
int value = -5;
if (value >= 0) {
printf("%d is non-negative.\n", value);
} else {
printf("%d is negative.\n", value);
}
// Check pass or fail
int score = 45;
if (score >= 50) {
printf("Result: PASS\n");
} else {
printf("Result: FAIL\n");
}
}
/* ============================================================
* EXAMPLE 3: ELSE IF LADDER
* ============================================================ */
void example_else_if() {
printf("\n=== Example 3: else if Ladder ===\n");
int score = 78;
printf("Score: %d\n", score);
printf("Grade: ");
if (score >= 90) {
printf("A (Excellent!)\n");
} else if (score >= 80) {
printf("B (Good)\n");
} else if (score >= 70) {
printf("C (Average)\n");
} else if (score >= 60) {
printf("D (Below Average)\n");
} else if (score >= 50) {
printf("E (Pass)\n");
} else {
printf("F (Fail)\n");
}
}
/* ============================================================
* EXAMPLE 4: NESTED IF STATEMENTS
* ============================================================ */
void example_nested_if() {
printf("\n=== Example 4: Nested if Statements ===\n");
int age = 25;
int hasLicense = 1; // 1 = true, 0 = false
int hasInsurance = 1;
printf("Age: %d, License: %s, Insurance: %s\n",
age,
hasLicense ? "Yes" : "No",
hasInsurance ? "Yes" : "No");
if (age >= 18) {
printf(" Age check: PASSED\n");
if (hasLicense) {
printf(" License check: PASSED\n");
if (hasInsurance) {
printf(" Insurance check: PASSED\n");
printf(" Result: You can drive!\n");
} else {
printf(" Insurance check: FAILED\n");
printf(" Result: Get insurance first.\n");
}
} else {
printf(" License check: FAILED\n");
printf(" Result: Get a driving license first.\n");
}
} else {
printf(" Age check: FAILED\n");
printf(" Result: Too young to drive.\n");
}
}
/* ============================================================
* EXAMPLE 5: LOGICAL OPERATORS IN CONDITIONS
* ============================================================ */
void example_logical_operators() {
printf("\n=== Example 5: Logical Operators ===\n");
int age = 25;
int income = 50000;
int creditScore = 720;
printf("Age: %d, Income: $%d, Credit Score: %d\n",
age, income, creditScore);
// AND operator (&&)
if (age >= 21 && income >= 30000) {
printf(" Meets basic requirements (age AND income)\n");
}
// OR operator (||)
if (creditScore >= 750 || income >= 100000) {
printf(" Qualifies for premium rate (good credit OR high income)\n");
} else {
printf(" Standard rate applies\n");
}
// NOT operator (!)
int isBanned = 0;
if (!isBanned) {
printf(" Account is in good standing\n");
}
// Combined operators
if ((age >= 21 && income >= 30000) && !isBanned) {
printf(" Application: APPROVED\n");
}
}
/* ============================================================
* EXAMPLE 6: CHECKING RANGES
* ============================================================ */
void example_ranges() {
printf("\n=== Example 6: Range Checking ===\n");
int hour = 14;
printf("Hour: %d\n", hour);
// Check time of day
if (hour >= 0 && hour < 6) {
printf(" It's night time.\n");
} else if (hour >= 6 && hour < 12) {
printf(" Good morning!\n");
} else if (hour >= 12 && hour < 17) {
printf(" Good afternoon!\n");
} else if (hour >= 17 && hour < 21) {
printf(" Good evening!\n");
} else if (hour >= 21 && hour < 24) {
printf(" It's night time.\n");
} else {
printf(" Invalid hour!\n");
}
// Character range check
char ch = 'G';
printf("\nCharacter: '%c'\n", ch);
if (ch >= 'A' && ch <= 'Z') {
printf(" It's an uppercase letter.\n");
} else if (ch >= 'a' && ch <= 'z') {
printf(" It's a lowercase letter.\n");
} else if (ch >= '0' && ch <= '9') {
printf(" It's a digit.\n");
} else {
printf(" It's a special character.\n");
}
}
/* ============================================================
* EXAMPLE 7: TERNARY OPERATOR
* ============================================================ */
void example_ternary() {
printf("\n=== Example 7: Ternary Operator ===\n");
int a = 10, b = 20;
// Find maximum using ternary
int max = (a > b) ? a : b;
printf("max(%d, %d) = %d\n", a, b, max);
// Find minimum
int min = (a < b) ? a : b;
printf("min(%d, %d) = %d\n", a, b, min);
// Absolute value
int x = -15;
int abs_x = (x < 0) ? -x : x;
printf("abs(%d) = %d\n", x, abs_x);
// Conditional text
int isOnline = 1;
printf("Status: %s\n", isOnline ? "Online" : "Offline");
// Even/Odd
int num = 7;
printf("%d is %s\n", num, (num % 2 == 0) ? "even" : "odd");
// Nested ternary (use sparingly!)
int score = 75;
char grade = (score >= 90) ? 'A' :
(score >= 80) ? 'B' :
(score >= 70) ? 'C' :
(score >= 60) ? 'D' : 'F';
printf("Score %d = Grade %c\n", score, grade);
}
/* ============================================================
* EXAMPLE 8: SHORT-CIRCUIT EVALUATION
* ============================================================ */
void example_short_circuit() {
printf("\n=== Example 8: Short-Circuit Evaluation ===\n");
int a = 10, b = 0;
// Safe division using short-circuit
printf("a = %d, b = %d\n", a, b);
if (b != 0 && a / b > 2) {
printf(" Ratio is greater than 2\n");
} else {
printf(" Cannot compute or ratio <= 2\n");
}
// Demonstrating short-circuit with function
printf("\nDemonstrating evaluation order:\n");
// In this OR, if first is true, second is not checked
int isAdmin = 1;
printf("isAdmin = %d\n", isAdmin);
if (isAdmin || (printf(" This won't print\n"), 0)) {
printf(" Access granted (first condition was true)\n");
}
// Reset
isAdmin = 0;
printf("\nisAdmin = %d\n", isAdmin);
if (isAdmin || (printf(" Second condition checked\n"), 1)) {
printf(" Access granted via second condition\n");
}
}
/* ============================================================
* EXAMPLE 9: COMMON PATTERNS
* ============================================================ */
void example_patterns() {
printf("\n=== Example 9: Common Patterns ===\n");
// Pattern 1: Validation chain (early return)
printf("Validation pattern:\n");
int inputValue = 50;
if (inputValue < 0) {
printf(" Error: Value cannot be negative\n");
} else if (inputValue > 100) {
printf(" Error: Value cannot exceed 100\n");
} else if (inputValue == 0) {
printf(" Warning: Value is zero\n");
} else {
printf(" Value %d is valid!\n", inputValue);
}
// Pattern 2: State checking
printf("\nState checking pattern:\n");
int state = 2; // 0=idle, 1=running, 2=paused, 3=stopped
if (state == 0) {
printf(" System is idle\n");
} else if (state == 1) {
printf(" System is running\n");
} else if (state == 2) {
printf(" System is paused\n");
} else if (state == 3) {
printf(" System is stopped\n");
} else {
printf(" Unknown state: %d\n", state);
}
// Pattern 3: Boundary checking
printf("\nBoundary checking pattern:\n");
int index = 5;
int arraySize = 10;
if (index >= 0 && index < arraySize) {
printf(" Index %d is within bounds [0, %d)\n", index, arraySize);
} else {
printf(" Index %d is out of bounds!\n", index);
}
}
/* ============================================================
* EXAMPLE 10: COMPARING DIFFERENT TYPES
* ============================================================ */
void example_type_comparisons() {
printf("\n=== Example 10: Type Comparisons ===\n");
// Integer comparison
int num1 = 10, num2 = 20;
if (num1 < num2) {
printf("%d < %d: TRUE\n", num1, num2);
}
// Character comparison (ASCII values)
char c1 = 'A', c2 = 'B'; // A=65, B=66
if (c1 < c2) {
printf("'%c' < '%c': TRUE (ASCII %d < %d)\n", c1, c2, c1, c2);
}
// Float comparison with tolerance
float f1 = 0.1f + 0.2f;
float f2 = 0.3f;
float epsilon = 0.0001f;
printf("\nFloat comparison:\n");
printf(" 0.1 + 0.2 = %.10f\n", f1);
printf(" 0.3 = %.10f\n", f2);
// Direct comparison (may fail!)
if (f1 == f2) {
printf(" Direct: Equal\n");
} else {
printf(" Direct: NOT Equal (precision issue!)\n");
}
// Comparison with tolerance
if (fabsf(f1 - f2) < epsilon) {
printf(" With tolerance: Approximately equal\n");
}
// Pointer comparison with NULL
int *ptr = NULL;
if (ptr == NULL) {
printf("\nPointer is NULL\n");
}
}
/* ============================================================
* MAIN FUNCTION
* ============================================================ */
int main() {
printf("╔════════════════════════════════════════════════╗\n");
printf("║ IF, ELSE, ELSE IF STATEMENTS - EXAMPLES ║\n");
printf("║ Decision-making in C ║\n");
printf("╚════════════════════════════════════════════════╝\n");
example_basic_if();
example_if_else();
example_else_if();
example_nested_if();
example_logical_operators();
example_ranges();
example_ternary();
example_short_circuit();
example_patterns();
example_type_comparisons();
printf("\n=== All Examples Completed! ===\n");
return 0;
}