1: Introduction to if, else if, and else Statements
Conditional statements allow us to execute specific blocks of code based on certain conditions in C programming.
-
if Statement:
int age = 20;
if (age >= 18) {
printf("You are an adult.n");
}
-
else Statement:
int age = 15;
if (age >= 18) {
printf("You are an adult.n");
} else {
printf("You are a minor.n");
}
-
else if Statement:
int score = 75;
if (score >= 90) {
printf("Grade An");
} else if (score >= 80) {
printf("Grade Bn");
} else if (score >= 70) {
printf("Grade Cn");
} else {
printf("Grade Fn");
}
2: Nested if Statements
Nested if statements allow us to include one if or else if statement inside another.
- Example:
int num = 10;
if (num > 0) {
if (num % 2 == 0) {
printf("Positive even numbern");
} else {
printf("Positive odd numbern");
}
} else {
printf("Not a positive numbern");
}
3: Ternary Operator
The ternary operator (?:
) provides a shorthand way to write if-else statements in a single line.
-
Syntax:
condition ? expression_if_true : expression_if_false;
-
Example:
int num = 12;
num % 2 == 0 ? printf("Evenn") : printf("Oddn");
4: Practice and Examples
- Practice Exercise:
- Write a program that prompts the user to enter an integer and checks if it’s positive, negative, or zero.
- Use if, else if, and else statements along with appropriate output.
int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);
if (num > 0) {
printf("Positive numbern");
} else if (num < 0) {
printf("Negative numbern");
} else {
printf("Zeron");
}
return 0;
}
In the next lesson, we’ll explore more complex control structures including switch statements and loops in C. Practice writing and understanding conditional statements to enhance your programming skills.