The if...else
statement in C is a conditional control structure that allows you to execute different blocks of code depending on whether a specified condition is true or false. It is one of the most commonly used decision-making structures in C programming.
Syntax
if (condition) { // Code to execute if the condition is true } else { // Code to execute if the condition is false }
condition
: A Boolean expression (or any expression that can be evaluated to true or false).true
: The block of code inside theif
part is executed if the condition is true (non-zero).false
: The block of code inside theelse
part is executed if the condition is false (zero).
Example 1: Basic if...else
#include <stdio.h> int main() { int number = 10; if (number > 0) { printf("The number is positive.\n"); } else { printf("The number is non-positive.\n"); } return 0; }
Output:
The number is positive.
Example 2: if...else
with Different Conditions
You can use multiple conditions with the if...else
statement to handle different cases.
#include <stdio.h> int main() { int number = -5; if (number > 0) { printf("The number is positive.\n"); } else if (number < 0) { printf("The number is negative.\n"); } else { printf("The number is zero.\n"); } return 0; }
Output:
The number is negative.
Example 3: Nested if...else
You can also nest if...else
statements inside each other to handle more complex conditions.
#include <stdio.h> int main() { int number = 7; if (number > 0) { if (number % 2 == 0) { printf("The number is positive and even.\n"); } else { printf("The number is positive and odd.\n"); } } else { printf("The number is non-positive.\n"); } return 0; }
Output:
The number is positive and odd.
Example 4: if...else
with Boolean Expressions
The condition in the if
statement can be any expression that evaluates to a Boolean value (either true
or false
).
#include <stdio.h> int main() { int x = 3, y = 5; if (x == y) { printf("x and y are equal.\n"); } else { printf("x and y are not equal.\n"); } return 0; }
Output:
x and y are not equal.
Example 5: if...else
with Logical Operators
You can combine multiple conditions using logical operators (&&
for AND, ||
for OR) in the if
condition.
#include <stdio.h> int main() { int age = 25; int hasLicense = 1; // 1 represents true, 0 represents false if (age >= 18 && hasLicense) { printf("You are eligible to drive.\n"); } else { printf("You are not eligible to drive.\n"); } return 0; }
Output:
You are eligible to drive.
Summary
- The
if...else
statement evaluates a condition, and based on whether it’s true or false, it executes one of two blocks of code. - You can chain multiple
else if
clauses to handle more than two possible conditions. - Conditions can include relational comparisons, logical operators, and complex expressions.
- It’s a foundational control structure for making decisions in C programs.