The if-else statement in C++ is a control flow structure used to execute code conditionally. It allows you to check a boolean condition (an expression that evaluates to true or false) and execute different blocks of code depending on whether the condition is true or false.
Syntax:
if (condition)
{
// Code to execute if the condition is true
}
else
{
// Code to execute if the condition is false
}
Example:
#include <iostream>
using namespace std;
int main() {
int age = 15;
// Checking if the person is eligible to vote
if (age >= 18)
{
cout <<"You are eligible to vote."<< endl;
} else {
cout <<"You are not eligible to vote."<< endl;
}
return 0;
}
Output:
Example: If number is not positive
#include <iostream>
using namespace std;
int main() {
int number = -20;
// Checking if the number is positive
if (number > 0)
{
cout <<"Number is positive"<< endl;
} else {
cout <<"Number is not positive"<< endl;
}
return 0;
}
Explanation:
- Condition: number >= 0 is the condition being checked.
- Since number is less than 0, then condition evaluates to false.
Output:
C++ If else statement – Interview Questions
Q 1: What is the purpose of if-else?
Ans: To execute one block if condition is true and another if false.
Q 2: How many blocks are there in if-else?
Ans: Two blocks.
Q 3: Is else mandatory?
Ans: No.
Q 4: Can if-else handle multiple conditions?
Ans: No, use else-if for that.
Q 5: Does if-else improve program flow control?
Ans: Yes.
C++ If else statement – Objective Questions (MCQs)
Q1. What is the purpose of the if-else statement?
Q2. What will be the output of this code?
int x = 8;
if (x < 5)
cout << "Small";
else
cout << "Big";
Q3. In an if-else structure, when the condition is true:
Q4. Can we have multiple else blocks with one if?
Q5. What is the output of the following code?
int x = 10;
if (x == 5)
cout << "Equal";
else
cout << "Not Equal";