Table of contents
1. What is an if statement?2. Basic syntax of an if statement
3. Using else and else if
4. Nested if statements
5. Common mistake
6. Best practices
The if
statement allows developers to execute code under a given condition. In this lesson, I will give practical examples of if
statement in C.
The simplest form of an if
statement evaluates a condition and executes a block of code if the condition is true.
if (condition) {
// code to execute if condition is true
}
Example
#include <stdio.h>
int main() {
int number = 10;
if (number > 0) {
printf("The number is positive.\n");
}
return 0;
}
To handle multiple conditions, else
and else if
can be used in conjunction with the if
statement.
if (condition1) {
// code if condition1 is true
} else if (condition2) {
// code if condition2 is true
} else {
// code if none of the above conditions are true
}
#include <stdio.h>
int main() {
int score = 75;
if (score >= 90) {
printf("Grade: A\n");
} else if (score >= 80) {
printf("Grade: B\n");
} else if (score >= 70) {
printf("Grade: C\n");
} else {
printf("Grade: F\n");
}
return 0;
}
Conditions can be nested within each other to handle more complex decision-making scenarios.
if (condition1) {
if (condition2) {
// code if both condition1 and condition2 are true
}
}
#include <stdio.h>
int main() {
int age = 25;
int hasLicense = 1;
if (age >= 18) {
if (hasLicense) {
printf("You are eligible to drive.\n");
} else {
printf("You need a driver's license to drive.\n");
}
} else {
printf("You are not old enough to drive.\n");
}
return 0;
}
Omitting braces for single statements
While C allows omitting braces for single statements, it can lead to bugs, especially when adding more statements later.
if (condition)
printf("Condition is true.\n");
// Adding another statement here without braces can cause unexpected behavior
printf("This always prints.\n");
Proper usage with braces
if (condition) {
printf("Condition is true.\n");
// Additional statements
printf("This also prints only if condition is true.\n");
}
if
statements or helper functions.Example
#include <stdio.h>
int main() {
int a = 5, b = 10;
int max = (a > b) ? a : b;
printf("Maximum value is %d\n", max);
return 0;
}
Author
Dr. Roger Ianjamasimanana