In C programming, an if-else statement is used to make decisions based on conditions. It allows the program to execute a block of code if a specified condition is true, or a different block of code if the condition is false.
Syntax:
if (condition) {
// Block of code executed if the condition is true
} else {
// Block of code executed if the condition is false
}
Example:
#include <stdio.h>
int main() {
int age = 15;
// Checking if the person is eligible to vote
if (age >= 18)
{
printf("You are eligible to vote.");
} else {
printf("You are not eligible to vote.");
}
return 0;
}
Output:
You are not eligible to vote.
Example: If number is not positive
#include <stdio.h>
int main() {
int number = -20;
// Checking if the number is positive
if (number > 0)
{
printf("Number is positive");
} else {
printf("Number is not positive");
}
return 0;
}
Explanation:
- Condition: number >= 0 is the condition being checked.
- Since number is less than 0, then condition evaluates to false.
Output:
Number is not positive
C if-else statement – Interview Questions
Q 1: What is an if-else statement in C?
Ans: It executes one block if the condition is true and another block if it is false.
Q 2: When should we use if-else?
Ans: When two mutually exclusive conditions need to be handled.
Q 3: Can an else block exist without an if?
Ans: No, an else must always be associated with an if.
Q 4: How many else blocks can an if have?
Ans: Only one else block.
Q 5: Is if-else faster than switch?
Ans: It depends on the use case; switch is often faster for multiple fixed values.
C if-else statement – Objective Questions (MCQs)
Q1. What is the main purpose of an if-else statement?
Q2. What is the output of the following code?
int x = 3;
if (x > 5)
printf("Big");
else
printf("Small");
Q3. Which of the following is invalid syntax?
Q4. Can an else exist without an if in C?
Q5. What will be the output?
int n = 0;
if (n)
printf("True");
else
printf("False");