An if statement in C++ is a conditional statement that allows you to execute a block of code only if a specific condition is true. It helps control the flow of the program based on whether a condition evaluates to true or false.
In an if-statement, the first (or only) statement is executed if the condition is true and the second statement (if it is specified) is executed otherwise.
Syntax:
if (condition) {
// Code to execute if condition is true
}
Example:
#include <iostream>
using namespace std;
int main() {
int age = 18;
// Checking if the person is eligible to vote
if (age >= 18)
{
cout << "You are eligible to vote."<< endl;
}
return 0;
}
In this example, if age>=18 then it will show message You are eligible to vote.
Output:
C++ If statement – Interview Questions
Q 1: What is an if statement in C++?
Q 2: What type of condition is used in an if statement?
Q 3: Can an if statement exist without else?
Q 4: What happens if the condition is false?
Q 5: Can we use relational operators in if conditions?
C++ If statement – Objective Questions (MCQs)
Q1. What is the correct syntax of an if statement in C++?
Q2. What will be the output of the following code?
int x = 10;
if (x > 5)
cout << "Hello";
Q3. In an if statement, the condition must evaluate to:
Q4. What happens if the condition in an if statement is false?
Q5. Which of the following conditions is valid in an if statement?