Conditions • Decision-Making • Program Flow Control
Programs often need to choose between multiple paths of execution. In C, decision-making is done using the if family of statements.
The if statement checks a condition (true/false) and executes code only when the condition is true.
Conditions typically use:
> < >= <= == !=&& || !if StatementThe simplest form executes a block only if the condition is true.
if (condition) {
// code runs when condition is true
}
#include <stdio.h>
int main() {
int age = 20;
if (age >= 18) {
printf("You are an adult.\n");
}
return 0;
}
Output: You are an adult.
if…else StatementUse this when you need to choose between two actions.
if (condition) {
// true block
} else {
// false block
}
#include <stdio.h>
int main() {
int n = -5;
if (n >= 0) {
printf("Positive\n");
} else {
printf("Negative\n");
}
return 0;
}
else if LadderUsed when there are multiple possible conditions.
#include <stdio.h>
int main() {
int marks = 82;
if (marks >= 90) {
printf("Grade A\n");
}
else if (marks >= 75) {
printf("Grade B\n");
}
else if (marks >= 50) {
printf("Grade C\n");
}
else {
printf("Fail\n");
}
return 0;
}
if StatementsYou can place one if statement inside another.
#include <stdio.h>
int main() {
int a = 10;
if (a > 0) {
if (a % 2 == 0) {
printf("Positive Even\n");
}
}
return 0;
}
| Type | Use Case |
|---|---|
| if | Single condition |
| if…else | Two-way decision |
| else if | Multiple conditions |
| Nested if | Decision inside another decision |
#include <stdio.h>
int main() {
int temp;
printf("Enter temperature: ");
scanf("%d", &temp);
if (temp > 40) {
printf("Very Hot");
}
else if (temp > 30) {
printf("Hot");
}
else if (temp > 20) {
printf("Warm");
}
else {
printf("Cold");
}
return 0;
}