Introduction to Conditionals
Conditional statements are the decision-makers of programming. They allow your program to choose different paths based on whether certain conditions are true or false - just like how you make decisions in real life based on circumstances.
What is a Conditional Statement?
A conditional statement is a programming construct that performs different actions depending on whether a condition evaluates to true or false. It controls the flow of execution in your program.
In C, conditions evaluate to integers: 0 means false, any non-zero value (typically 1) means true.
Why Do We Need Conditionals?
Without conditionals, programs would be like trains - they could only go in one direction, executing every line of code from top to bottom. With conditionals, programs become like cars that can take different routes based on conditions:
User Authentication
Check if password is correct before granting access to the system.
Input Validation
Verify that user input is within acceptable ranges before processing.
Game Logic
Determine player actions, check win/lose conditions, control enemy behavior.
Business Rules
Calculate discounts, taxes, or fees based on specific criteria.
Types of Conditional Statements in C
C provides several conditional constructs, each suited for different scenarios:
| Statement | Use Case | Example Scenario |
|---|---|---|
if |
Execute code only when condition is true | Check if user is adult before allowing access |
if-else |
Choose between two alternatives | Display "Pass" or "Fail" based on marks |
else-if ladder |
Choose among multiple alternatives | Assign grade (A, B, C, D, F) based on score |
nested if |
Complex multi-level decisions | Check eligibility based on age AND citizenship |
switch |
Select from many options based on a value | Menu selection (1=Add, 2=Delete, 3=View) |
How Conditionals Work
Every conditional follows this basic pattern:
// Basic conditional structure
if (condition) {
// Code to execute when condition is TRUE (non-zero)
}
// The condition is an expression that evaluates to true or false
// In C: 0 = false, non-zero = true
The if Statement
The if statement is the simplest form of decision-making. It executes a block
of code only when a specified condition is true. If the condition is false, the code block
is simply skipped and execution continues with the next statement.
if
like asking a yes/no question. "Is it raining?" If yes, take an umbrella. If no, just continue
on your way without doing anything special.
The if Statement
The if statement tests a condition and executes its code block only when the condition evaluates to true (non-zero). It provides one-way branching - either execute the block or skip it entirely.
Syntax: if (condition) { statements; }
Basic Syntax
// Syntax of if statement
if (condition) {
// Code to execute if condition is true
// Can have multiple statements here
}
// Single statement can omit braces (but not recommended)
if (condition)
single_statement;
{} even for single statements. This prevents bugs when you later
add more statements and forget to add braces.
Simple Examples
Age Check
int age = 18;
// Check if person is an adult
if (age >= 18) {
printf("You are an adult.\n");
}
printf("Program continues...\n");
// Output:
// You are an adult.
// Program continues...
age >= 18 evaluates to 1 (true)
because 18 is greater than or equal to 18. Since the condition is true, the printf inside
the if block executes. Regardless of the condition result, "Program continues..." always prints.
Temperature Warning
float temperature = 102.5;
// Check for fever
if (temperature > 100.4) {
printf("Warning: You have a fever!\n");
printf("Temperature: %.1f F\n", temperature);
printf("Please consult a doctor.\n");
}
// Output:
// Warning: You have a fever!
// Temperature: 102.5 F
// Please consult a doctor.
Division Safety Check
int numerator = 10;
int denominator = 0;
// Prevent division by zero
if (denominator != 0) {
int result = numerator / denominator;
printf("Result: %d\n", result);
}
printf("Calculation complete.\n");
// Output:
// Calculation complete.
// (No division performed - condition was false)
denominator != 0 is false, so the division (which would crash the program)
never happens.
Common if Statement Patterns
Input Validation
#include <stdio.h>
int main() {
int score;
printf("Enter your score (0-100): ");
scanf("%d", &score);
// Validate input range
if (score >= 0 && score <= 100) {
printf("Valid score: %d\n", score);
}
// Check for invalid input
if (score < 0 || score > 100) {
printf("Invalid score! Must be between 0 and 100.\n");
}
return 0;
}
Even/Odd Check
int number = 7;
// Check if even using modulus
if (number % 2 == 0) {
printf("%d is even.\n", number);
}
if (number % 2 != 0) {
printf("%d is odd.\n", number);
}
// Output: 7 is odd.
Practice Questions: if Statement
Problem: Write a program that checks if a given number is positive and prints a message.
Given:
int num = 25;
Task: Write a program that checks if the number is positive and prints a message.
Expected output: 25 is a positive number.
Show Solution
#include <stdio.h>
int main() {
int num = 25;
if (num > 0) {
printf("%d is a positive number.\n", num);
}
return 0;
}
Given:
int age = 21;
Task: Write a program to check if a person is eligible to vote (age >= 18).
Expected output: You are eligible to vote!
Show Solution
#include <stdio.h>
int main() {
int age = 21;
if (age >= 18) {
printf("You are eligible to vote!\n");
}
return 0;
}
Given:
int num = 15;
Task: Check if a number is divisible by both 3 AND 5.
Expected output: 15 is divisible by both 3 and 5
Hint: Use the modulus operator (%) and logical AND (&&).
Show Solution
#include <stdio.h>
int main() {
int num = 15;
if (num % 3 == 0 && num % 5 == 0) {
printf("%d is divisible by both 3 and 5\n", num);
}
return 0;
}
// Note: 15 % 3 = 0 (true) AND 15 % 5 = 0 (true)
// Both conditions true, so message prints
The if-else Statement
The if-else statement extends the basic if by providing an alternative action
when the condition is false. It creates two-way branching - your program will always execute
exactly one of the two blocks, never both and never neither.
The if-else Statement
The if-else statement provides two-way decision making. If the condition is true, the first block executes. If the condition is false, the else block executes. Exactly one block will always run.
Syntax: if (condition) { block1 } else { block2 }
Basic Syntax
// Syntax of if-else statement
if (condition) {
// Code to execute if condition is TRUE
} else {
// Code to execute if condition is FALSE
}
// One block ALWAYS executes - never both, never neither
Practical Examples
Pass or Fail
int marks = 65;
int passingMarks = 50;
if (marks >= passingMarks) {
printf("Congratulations! You passed.\n");
printf("Your marks: %d\n", marks);
} else {
printf("Sorry, you failed.\n");
printf("You needed %d more marks.\n", passingMarks - marks);
}
// Output:
// Congratulations! You passed.
// Your marks: 65
Even or Odd
int number = 17;
if (number % 2 == 0) {
printf("%d is an even number.\n", number);
} else {
printf("%d is an odd number.\n", number);
}
// Output: 17 is an odd number.
Age Classification
int age = 15;
if (age >= 18) {
printf("You are an adult.\n");
printf("You can vote and drive.\n");
} else {
printf("You are a minor.\n");
printf("You cannot vote yet.\n");
printf("Wait %d more years.\n", 18 - age);
}
// Output:
// You are a minor.
// You cannot vote yet.
// Wait 3 more years.
Finding Maximum of Two Numbers
int a = 25, b = 40;
int max;
if (a > b) {
max = a;
} else {
max = b;
}
printf("The maximum of %d and %d is %d\n", a, b, max);
// Output: The maximum of 25 and 40 is 40
The Ternary Operator (Shorthand if-else)
For simple if-else assignments, C provides a compact one-line alternative called the
ternary operator (?:). It's called "ternary" because it takes three operands.
// Ternary operator syntax
// variable = (condition) ? value_if_true : value_if_false;
int a = 25, b = 40;
// Using if-else
int max1;
if (a > b) {
max1 = a;
} else {
max1 = b;
}
// Same logic using ternary operator
int max2 = (a > b) ? a : b;
printf("max1 = %d, max2 = %d\n", max1, max2); // Both are 40
When to Use Ternary
- Simple value assignments
- Return statements
- Printf arguments
- Single-line decisions
When to Avoid Ternary
- Multiple statements needed
- Complex conditions
- Nested ternary (hard to read)
- When clarity is more important
More Ternary Examples
int age = 20;
int score = 85;
// Print eligibility
printf("%s\n", (age >= 18) ? "Adult" : "Minor"); // Adult
// Calculate grade status
char status = (score >= 50) ? 'P' : 'F'; // P (Pass)
// Find absolute value
int num = -5;
int absolute = (num >= 0) ? num : -num; // 5
// Singular/plural
int items = 1;
printf("You have %d item%s\n", items, (items == 1) ? "" : "s");
// Output: You have 1 item
Practice Questions: if-else Statement
Given:
int num = -7;
Task: Write a program to check if a number is positive or negative.
Expected output: -7 is a negative number.
Show Solution
#include <stdio.h>
int main() {
int num = -7;
if (num >= 0) {
printf("%d is a positive number.\n", num);
} else {
printf("%d is a negative number.\n", num);
}
return 0;
}
Given:
int x = 45, y = 30;
Task: Write a program to find and print the minimum of two numbers.
Expected output: Minimum of 45 and 30 is 30
Show Solution
#include <stdio.h>
int main() {
int x = 45, y = 30;
int min;
if (x < y) {
min = x;
} else {
min = y;
}
printf("Minimum of %d and %d is %d\n", x, y, min);
// Using ternary operator:
// int min = (x < y) ? x : y;
return 0;
}
Given:
int year = 2024;
Task: Check if a year is divisible by 4 (simplified leap year check).
Expected output: 2024 is a leap year.
Show Solution
#include <stdio.h>
int main() {
int year = 2024;
// Simplified check (divisible by 4)
if (year % 4 == 0) {
printf("%d is a leap year.\n", year);
} else {
printf("%d is not a leap year.\n", year);
}
return 0;
}
// Note: Complete leap year logic is more complex:
// Divisible by 4 AND (not divisible by 100 OR divisible by 400)
The else-if Ladder
When you need to choose from more than two alternatives, the else-if ladder
(also called else-if chain) is your tool. It tests multiple conditions in sequence and
executes the block for the first true condition it finds.
The else-if Ladder
The else-if ladder chains multiple conditions together. Conditions are tested top-to-bottom, and the first true condition's block executes. If no condition is true, the optional final else block runs as a default.
Only ONE block executes, even if multiple conditions could be true. Order matters!
Basic Syntax
// Syntax of else-if ladder
if (condition1) {
// Executes if condition1 is true
} else if (condition2) {
// Executes if condition1 is false AND condition2 is true
} else if (condition3) {
// Executes if condition1 and condition2 are false AND condition3 is true
} else {
// Default: executes if ALL conditions are false
// This else is optional
}
Classic Example: Grade Calculator
#include <stdio.h>
int main() {
int score = 78;
char grade;
if (score >= 90) {
grade = 'A';
printf("Excellent!\n");
} else if (score >= 80) {
grade = 'B';
printf("Very Good!\n");
} else if (score >= 70) {
grade = 'C';
printf("Good!\n");
} else if (score >= 60) {
grade = 'D';
printf("Satisfactory.\n");
} else {
grade = 'F';
printf("Needs improvement.\n");
}
printf("Your grade: %c\n", grade);
return 0;
}
// Output:
// Good!
// Your grade: C
More Practical Examples
Discount Calculator
float purchaseAmount = 750.0;
float discount;
if (purchaseAmount >= 1000) {
discount = 0.20; // 20% discount for purchases >= 1000
} else if (purchaseAmount >= 500) {
discount = 0.10; // 10% discount for purchases >= 500
} else if (purchaseAmount >= 100) {
discount = 0.05; // 5% discount for purchases >= 100
} else {
discount = 0.0; // No discount for purchases < 100
}
float discountAmount = purchaseAmount * discount;
float finalPrice = purchaseAmount - discountAmount;
printf("Original: $%.2f\n", purchaseAmount);
printf("Discount: %.0f%% ($%.2f)\n", discount * 100, discountAmount);
printf("Final Price: $%.2f\n", finalPrice);
// Output:
// Original: $750.00
// Discount: 10% ($75.00)
// Final Price: $675.00
Day of Week
int day = 3; // 1=Monday, 2=Tuesday, ..., 7=Sunday
if (day == 1) {
printf("Monday - Start of the work week\n");
} else if (day == 2) {
printf("Tuesday\n");
} else if (day == 3) {
printf("Wednesday - Midweek\n");
} else if (day == 4) {
printf("Thursday\n");
} else if (day == 5) {
printf("Friday - TGIF!\n");
} else if (day == 6) {
printf("Saturday - Weekend!\n");
} else if (day == 7) {
printf("Sunday - Weekend!\n");
} else {
printf("Invalid day number\n");
}
// Output: Wednesday - Midweek
BMI Category Calculator
float bmi = 24.5;
printf("Your BMI: %.1f - ", bmi);
if (bmi < 18.5) {
printf("Underweight\n");
} else if (bmi < 25.0) {
printf("Normal weight\n");
} else if (bmi < 30.0) {
printf("Overweight\n");
} else {
printf("Obese\n");
}
// Output: Your BMI: 24.5 - Normal weight
Nested Conditionals
Sometimes you need to check conditions within conditions. This is called nesting - placing one if statement inside another. While powerful, be careful not to nest too deeply as it becomes hard to read and maintain.
#include <stdio.h>
int main() {
int age = 25;
int hasLicense = 1; // 1 = true
if (age >= 18) {
printf("You are an adult.\n");
if (hasLicense) {
printf("You can drive a car.\n");
} else {
printf("You need to get a license to drive.\n");
}
} else {
printf("You are a minor.\n");
printf("You cannot drive yet.\n");
}
return 0;
}
// Output:
// You are an adult.
// You can drive a car.
&&, ||) to combine conditions or extract
logic into separate functions.
Practice Questions: else-if Ladder
Given:
int age = 35;
Task: Categorize age into Child (0-12), Teen (13-19), Adult (20-59), Senior (60+).
Expected output: You are an Adult.
Show Solution
#include <stdio.h>
int main() {
int age = 35;
if (age < 13) {
printf("You are a Child.\n");
} else if (age < 20) {
printf("You are a Teen.\n");
} else if (age < 60) {
printf("You are an Adult.\n");
} else {
printf("You are a Senior.\n");
}
return 0;
}
Given:
int a = 25, b = 47, c = 33;
Task: Find and print the largest of three numbers.
Expected output: The largest number is 47
Show Solution
#include <stdio.h>
int main() {
int a = 25, b = 47, c = 33;
int largest;
if (a >= b && a >= c) {
largest = a;
} else if (b >= a && b >= c) {
largest = b;
} else {
largest = c;
}
printf("The largest number is %d\n", largest);
return 0;
}
Task: Implement complete leap year logic: divisible by 4, but not by 100 unless also divisible by 400.
Test Cases:
- 2024 - Leap year (divisible by 4)
- 1900 - NOT leap year (divisible by 100 but not 400)
- 2000 - Leap year (divisible by 400)
Show Solution
#include <stdio.h>
int main() {
int year = 2000;
if (year % 400 == 0) {
printf("%d is a leap year.\n", year);
} else if (year % 100 == 0) {
printf("%d is NOT a leap year.\n", year);
} else if (year % 4 == 0) {
printf("%d is a leap year.\n", year);
} else {
printf("%d is NOT a leap year.\n", year);
}
return 0;
}
// Logic explanation:
// 1. If divisible by 400 -> leap year (e.g., 2000)
// 2. If divisible by 100 (but not 400) -> NOT leap year (e.g., 1900)
// 3. If divisible by 4 (but not 100) -> leap year (e.g., 2024)
// 4. Otherwise -> NOT leap year (e.g., 2023)
The switch Statement
The switch statement provides an elegant alternative to long else-if ladders
when you're comparing a single variable against multiple constant values. It's cleaner,
more readable, and often more efficient for menu-driven programs.
The switch Statement
The switch statement evaluates an expression and jumps directly to the matching case label. It's designed for comparing a single variable against multiple constant integer or character values.
Important: Always include break
statements unless you intentionally want fall-through behavior.
Basic Syntax
// Syntax of switch statement
switch (expression) {
case constant1:
// Code for constant1
break;
case constant2:
// Code for constant2
break;
case constant3:
// Code for constant3
break;
default:
// Code if no case matches
break;
}
Example: Day of the Week
#include <stdio.h>
int main() {
int day = 3;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
case 6:
printf("Saturday\n");
break;
case 7:
printf("Sunday\n");
break;
default:
printf("Invalid day number\n");
break;
}
return 0;
}
// Output: Wednesday
day (which is 3), then
jumps directly to case 3:. It prints "Wednesday" and the break
exits the switch. Without break, execution would "fall through" to case 4, 5, etc.
Example: Simple Calculator
#include <stdio.h>
int main() {
int num1 = 20, num2 = 5;
char operator = '/';
float result;
switch (operator) {
case '+':
result = num1 + num2;
printf("%d + %d = %.2f\n", num1, num2, result);
break;
case '-':
result = num1 - num2;
printf("%d - %d = %.2f\n", num1, num2, result);
break;
case '*':
result = num1 * num2;
printf("%d * %d = %.2f\n", num1, num2, result);
break;
case '/':
if (num2 != 0) {
result = (float)num1 / num2;
printf("%d / %d = %.2f\n", num1, num2, result);
} else {
printf("Error: Division by zero!\n");
}
break;
case '%':
if (num2 != 0) {
printf("%d %% %d = %d\n", num1, num2, num1 % num2);
} else {
printf("Error: Division by zero!\n");
}
break;
default:
printf("Invalid operator: %c\n", operator);
break;
}
return 0;
}
// Output: 20 / 5 = 4.00
Understanding Fall-through
Without break, execution "falls through" to the next case. This is usually a
bug, but sometimes it's intentional when multiple cases share the same code:
Accidental Fall-through (Bug!)
int day = 1;
switch (day) {
case 1:
printf("Monday\n");
// Missing break! Falls through to case 2
case 2:
printf("Tuesday\n");
break;
default:
printf("Other day\n");
}
// Output (unexpected!):
// Monday
// Tuesday
Intentional Fall-through (Useful!)
int day = 6;
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5:
printf("Weekday - Time to work!\n");
break;
case 6:
case 7:
printf("Weekend - Time to relax!\n");
break;
default:
printf("Invalid day\n");
}
// Output: Weekend - Time to relax!
switch vs if-else: When to Use Which?
Use switch When:
- Comparing ONE variable to multiple constants
- Values are integers or characters
- You have many options (menus, states)
- Cases are mutually exclusive
- Readability is important
Use if-else When:
- Conditions involve ranges (age > 18)
- Multiple variables in conditions
- Using float/double values
- Complex logical expressions
- Conditions aren't simple equality
Practice Questions: switch Statement
Given:
int month = 7;
Task: Given a month number (1-12), print the month name using switch statement.
Expected output: July
Show Solution
#include <stdio.h>
int main() {
int month = 7;
switch (month) {
case 1: printf("January\n"); break;
case 2: printf("February\n"); break;
case 3: printf("March\n"); break;
case 4: printf("April\n"); break;
case 5: printf("May\n"); break;
case 6: printf("June\n"); break;
case 7: printf("July\n"); break;
case 8: printf("August\n"); break;
case 9: printf("September\n"); break;
case 10: printf("October\n"); break;
case 11: printf("November\n"); break;
case 12: printf("December\n"); break;
default: printf("Invalid month\n"); break;
}
return 0;
}
Given:
char ch = 'E';
Task: Check if a character is a vowel or consonant using switch statement.
Expected output: E is a vowel.
Hint: Use case fall-through for grouping vowels together.
Show Solution
#include <stdio.h>
int main() {
char ch = 'E';
// Convert to lowercase for easier checking
if (ch >= 'A' && ch <= 'Z') {
ch = ch + 32; // Convert to lowercase
}
switch (ch) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
printf("%c is a vowel.\n", ch - 32); // Print uppercase
break;
default:
if ((ch >= 'a' && ch <= 'z')) {
printf("%c is a consonant.\n", ch - 32);
} else {
printf("Not an alphabet.\n");
}
break;
}
return 0;
}
Given:
int month = 4;
Task: Print the number of days in a given month (ignore leap years).
Expected output: Month 4 has 30 days.
Hint: Group months with same days using case fall-through.
Show Solution
#include <stdio.h>
int main() {
int month = 4;
int days;
switch (month) {
case 1: case 3: case 5: case 7:
case 8: case 10: case 12:
days = 31;
break;
case 4: case 6: case 9: case 11:
days = 30;
break;
case 2:
days = 28; // Ignoring leap years
break;
default:
days = 0;
printf("Invalid month!\n");
break;
}
if (days > 0) {
printf("Month %d has %d days.\n", month, days);
}
return 0;
}
Key Takeaways
if for Simple Decisions
Use if when you want to execute code only when a condition is true. The simplest form of branching.
if-else for Two Paths
Use if-else when you need exactly two alternatives. One block always executes, never both, never neither.
else-if for Multiple Options
Use else-if ladder when you have more than two alternatives. First true condition wins - order matters!
switch for Menu-Style
Use switch when comparing one variable to many constant values. Cleaner than long if-else chains.
Don't Forget break!
In switch statements, always use break unless you intentionally want fall-through behavior.
Always Use Braces
Even for single statements, use {} braces. It prevents bugs when adding more statements later.
Knowledge Check
Quick Quiz
Test what you've learned about C conditional statements