C If-Else
Conditional statements let your C program make decisions and execute different code paths based on conditions. C provides if, else, else if, and switch for controlling the flow of execution. This is the foundation of every non-trivial program.
1. Simple if Statement
#include <stdio.h>
int main() {
int age = 20;
if (age >= 18) {
printf("You are an adult\n");
}
return 0;
}
The if block runs only if the condition is true (non-zero). In C, any non-zero value is true, and 0 is false.
2. if-else Statement
int age = 15;
if (age >= 18) {
printf("You can vote\n");
} else {
printf("You cannot vote yet\n");
}
3. if-else-if Ladder
int marks = 78;
if (marks >= 90) {
printf("Grade: A+\n");
} else if (marks >= 80) {
printf("Grade: A\n");
} else if (marks >= 70) {
printf("Grade: B\n");
} else if (marks >= 60) {
printf("Grade: C\n");
} else {
printf("Grade: F\n");
}
// Output: Grade: B
The first true condition wins — the remaining checks are skipped.
4. Nested if
int age = 25;
int hasLicense = 1; // 1 = true
if (age >= 18) {
if (hasLicense) {
printf("You can drive\n");
} else {
printf("Get a license first\n");
}
} else {
printf("Too young to drive\n");
}
5. switch Statement
Efficient alternative to long if-else-if chains when comparing one value against multiple constant cases.
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;
default:
printf("Weekend\n");
}
// Output: Wednesday
Why break?
Without break, execution "falls through" to the next case — this can be intentional or a bug.
int x = 2;
switch (x) {
case 1:
case 2:
case 3:
printf("1, 2, or 3\n");
break;
default:
printf("Other\n");
}
Forgetting break in a switch case causes fall-through — the next case also executes. This is one of the most common C bugs. Always add break unless fall-through is intentional.
6. Ternary Operator (One-line if-else)
Compact way to write simple if-else: condition ? valueIfTrue : valueIfFalse.
int age = 20;
char* status = (age >= 18) ? "Adult" : "Minor";
printf("%s\n", status); // Adult
// Find max of two numbers
int a = 10, b = 20;
int max = (a > b) ? a : b;
printf("Max: %d\n", max);
Truthy and Falsy in C
In C, there's no separate boolean type in classic C. Instead:
- 0 = false
- Any non-zero value = true (including negative numbers)
if (1) printf("True\n"); // runs
if (0) printf("False\n"); // doesn't run
if (-5) printf("True\n"); // runs (non-zero)
if ("hello") printf("True\n"); // runs (non-zero address)
// Using stdbool.h for real booleans
#include <stdbool.h>
bool isActive = true;
if (isActive) printf("Active\n");
Common Comparison Mistakes
Mistake 1: Using = instead of ==
int x = 5;
// ❌ WRONG — assignment, always true
if (x = 10) {
printf("This always runs\n");
}
// ✅ CORRECT — comparison
if (x == 10) {
printf("This runs only if x is 10\n");
}
Mistake 2: Missing braces
// ❌ Wrong — only first line is in the if
if (x > 0)
printf("Positive\n");
printf("This always runs!\n");
// ✅ Correct
if (x > 0) {
printf("Positive\n");
printf("Only when x > 0\n");
}
Always use curly braces { } even for single statements — prevents bugs when you later add more lines. Modern C code style strongly encourages this.
Combining Conditions
int age = 22;
int hasId = 1;
if (age >= 18 && hasId) {
printf("Can enter\n");
}
if (age < 18 || !hasId) {
printf("Cannot enter\n");
}
// Range check
int marks = 85;
if (marks >= 80 && marks <= 100) {
printf("Grade A\n");
}
Real Example — Calculator with switch
#include <stdio.h>
int main() {
char op = '+';
int a = 10, b = 5;
switch (op) {
case '+':
printf("%d\n", a + b);
break;
case '-':
printf("%d\n", a - b);
break;
case '*':
printf("%d\n", a * b);
break;
case '/':
if (b != 0) {
printf("%.2f\n", (float) a / b);
} else {
printf("Cannot divide by zero\n");
}
break;
default:
printf("Invalid operator\n");
}
return 0;
}
// Output: 15
Real Example — Login Validation
#include <stdio.h>
#include <string.h>
int main() {
char username[20] = "admin";
char password[20] = "c123";
if (strcmp(username, "admin") == 0 && strcmp(password, "c123") == 0) {
printf("Login successful\n");
} else if (strcmp(username, "admin") != 0) {
printf("Invalid username\n");
} else {
printf("Wrong password\n");
}
return 0;
}
Note: In C, you can't compare strings with ==. Use strcmp() from string.h — returns 0 if equal.
switch vs if-else — When to Use Which?
- switch — comparing ONE variable against multiple constant values. Cleaner and often faster.
- if-else — complex conditions with ranges, logical operators, or different variable comparisons.
1. Write a C program to check if a number is positive, negative, or zero using if-else.
2. Check if a year is a leap year or not.
3. Print the day of the week for a number (1-7) using switch.
4. Find the largest of 3 numbers using nested if and ternary.
5. Build a simple calculator using switch for +, -, *, /.
Quick Revision
if— runs block if condition is true (non-zero).if-else— two-way branching.if-else-if— multiple conditions, first true wins.switch— compare one value against constants.break— prevents fall-through in switch.default— runs if no case matches.- Ternary:
cond ? a : b. - 0 = false, any non-zero = true.
- Use
==for comparison, not=. - Use
strcmp()for string comparison.
Interview Questions
Q: Difference between if-else and switch?
A: switch compares one value against multiple constants (int, char, enum). if-else supports any expression, ranges, and logical operators. switch is often cleaner for menu-style choices.
Q: Why is break needed in switch?
A: Without break, control "falls through" to the next case — all cases below the matched one also execute. This is sometimes intentional but usually a bug.
Q: What is the difference between = and == in C?
A: = is assignment — assigns a value to a variable. == is comparison — checks equality and returns 1 or 0. Using = in an if condition is a very common bug because it evaluates to the assigned value (usually non-zero, thus "true").
Q: What does the ternary operator do?
A: A compact if-else: condition ? valueIfTrue : valueIfFalse. Example: int max = (a > b) ? a : b;.
Q: How do you compare two strings in C?
A: Using strcmp() from <string.h>. It returns 0 if equal, negative if first is smaller, positive if first is larger. You cannot use == — it compares addresses, not content.
Q: Can switch work with floats and strings?
A: No. switch works only with integer types (int, char, enum) and expressions that evaluate to integers. Floats and strings cannot be used as switch expressions in C.
Want to Master C Programming?
Join our C Programming course in Varanasi — practical classes and career support at our Sarnath centre.