C if else Statement
The if else in C is an extension of the if statement which not only allows the program to execute one block of code if a condition is true, but also a different block if the condition is false. This enables making decisions with two possible outcomes.
Example:
#include <stdio.h>
int main() {
int n = 10;
if (n > 5) {
printf("%d is greater than 5",n);
}
else {
printf("%d is less than 5",n);
}
return 0;
}
Output
10 is greater than 5
Explanation: In the above program, the condition checks if the variable n is greater than 5. If true, if block is executed and it prints that n is greater than 5. If it evaluates to false, the else block is executed, printing that n is less than 5. Since n is 10, it prints "10 is greater than 5".
Syntax of if-else Statement
if (condition) {
// Code to execute if condition is true
}
else {
// Code to execute if condition is false
}
If the condition is true, then the code inside the if block is executed, otherwise the code inside the else block is executed. Any non-zero and non-null values are assumed to be true, and zero or null values are assumed to be false.
Working of if-else statement
The below flowchart explains the if else works in C:

- The if-else statement works by checking the condition defined with the if statement.
- If the condition defined in the
if
statement is true, then the code inside theif
block is executed and the rest is skipped. - If the condition evaluates to false, then the program executes the code in the
else
block
Examples of if-else
The below examples illustrate how to use the if else statement in C programs
Negative Number check using If-else statement
#include <stdio.h>
int main() {
int n = -7;
// If the number is negative
if (n < 0)
printf("Negative");
// If the number is not negative
else
printf("Not Negative");
return 0;
}
Output
Negative
Explanation: In this program, the if statements check if the given number n is less than 0 which means that the number is negative. As n is negative, it prints the if block. But if the number n was positive, the else block would have been executed.
Note: If long at the block only contains the single statement, we can skip the curly braces.
Check if Integer Lies in the Range
#include <stdio.h>
int main() {
int n = 6;
// Check if the number lies in the range [10, 20]
if (n >= 10 && n <= 20) {
printf("%d lies in range.", n);
}
else {
printf("%d does not lie in range.", n);
}
return 0;
}
Largest Among Three Numbers Using If-else
#include <stdio.h>
int main() {
int a = 1, b = 2, c = 11;
// Finding the largest by comparing using
// relational operators with if-else
if (a >= b) {
if (a >= c)
printf("%d", a);
else
printf("%d", c);
}
else {
if (b >= c)
printf("%d", b);
else
printf("%d", c);
}
return 0;
}
Output
11