C++ If statement

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:

You are eligible to vote.

C++ If statement – Interview Questions

Q 1: What is an if statement in C++?
Ans: It executes a block of code when a condition is true.
Q 2: What type of condition is used in an if statement?
Ans: A Boolean expression.
Q 3: Can an if statement exist without else?
Ans: Yes.
Q 4: What happens if the condition is false?
Ans: The if block is skipped.
Q 5: Can we use relational operators in if conditions?
Ans: Yes.

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?






Related C++ If statement Topics