In real life, we constantly make decisions.
For example:
If it is raining, take an umbrella. Otherwise, don't.
Programs also need to make decisions based on certain conditions. This is where conditional statements come in.
What are Conditional Statements?
Conditional statements allow a program to execute different blocks of code depending on whether a condition is true or false.
For example:
int age = 20;
if (age >= 18)
{
printf("You are eligible to vote.");
}
Since age >= 18 is true, the message is displayed.
if Statement
The if statement executes a block of code only when a condition is true.
Syntax
if (condition)
{
// code
}
Example
int marks = 80;
if (marks >= 40)
{
printf("Pass");
}
Output:
Pass
If the condition is false, the code inside if is simply skipped.
if-else Statement
Sometimes we want to perform one action if the condition is true and another if it is false.
For this, we use if-else.
int marks = 35;
if (marks >= 40)
{
printf("Pass");
}
else
{
printf("Fail");
}
Output:
Fail
Think of it as:
Condition
/ \
True False
↓ ↓
if else
if-else if-else
When we have multiple conditions, we can use an else if ladder.
For example, let's assign grades based on marks:
int marks = 85;
if (marks >= 90)
{
printf("A+");
}
else if (marks >= 80)
{
printf("A");
}
else if (marks >= 70)
{
printf("B");
}
else
{
printf("C");
}
Output:
A
C checks the conditions from top to bottom and executes the first matching block.
Nested if
An if statement can also be placed inside another if statement. This is called a nested if.
int age = 20;
int hasID = 1;
if (age >= 18)
{
if (hasID)
{
printf("Entry allowed");
}
}
Here, the second condition is checked only if the first condition is true.
switch Statement
When we need to choose between multiple fixed values, switch can make the code cleaner.
For example:
int day = 2;
switch (day)
{
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
default:
printf("Invalid day");
}
Output:
Tuesday
The break statement stops execution from continuing into the next case.
if-else vs switch
|
|
|---|---|
Works with complex conditions | Best for fixed values |
Supports ranges and comparisons | Matches specific case values |
Can check multiple expressions | Usually cleaner for menu-like choices |
Example: | Example: |
In Simple Words
Conditional statements allow a C program to make decisions.
The main conditional statements you'll use are:
ifif-elseif-else if-elseNested
ifswitch
For example, a program can check a student's marks and decide whether the student passed, failed, or received a particular grade.