Conditional statements in C allow programs to make decisions based on certain conditions. The if
and else
statements help control program flow based on logical conditions. This tutorial covers the basics of using if
, else
, and else if
statements.
The basic syntax of an if
statement in C is:
if (condition) {
// Code executes if condition is true
}
Adding an else
statement allows for alternate execution:
if (condition) {
// Code executes if condition is true
} else {
// Code executes if condition is false
}
Let's create a program that checks if a number is positive:
#include <stdio.h>
int main() {
int number = 10;
if (number > 0) {
printf("The number is positive.\n");
}
return 0;
}
If the condition is false, we use else
to handle the alternative case:
#include <stdio.h>
int main() {
int number = -5;
if (number > 0) {
printf("The number is positive.\n");
} else {
printf("The number is not positive.\n");
}
return 0;
}
The else if
statement allows multiple conditions:
#include <stdio.h>
int main() {
int number = 0;
if (number > 0) {
printf("The number is positive.\n");
} else if (number == 0) {
printf("The number is zero.\n");
} else {
printf("The number is negative.\n");
}
return 0;
}
Logical operators like &&
(AND), ||
(OR), and !
(NOT) can combine conditions:
#include <stdio.h>
int main() {
int age = 20;
if (age >= 18 && age <= 65) {
printf("You are an adult.\n");
} else {
printf("You are either too young or a senior.\n");
}
return 0;
}
If statements can be nested for complex logic:
#include <stdio.h>
int main() {
int score = 85;
if (score >= 50) {
printf("You passed.\n");
if (score >= 80) {
printf("You passed with distinction!\n");
}
} else {
printf("You failed.\n");
}
return 0;
}
else if
instead of multiple if
statements where possible.Understanding conditional statements is essential in programming. Try:
For further learning, check out the C Programming Tutorial.