The if statement is one of the most important decision-making tools in C++. It allows a program to perform certain actions only when a specific condition is true.

  • Purpose: To check a condition and execute a block of code if the condition evaluates to true.

  • Usage: Commonly used in conditional operations, comparisons, and decision-making tasks.

Syntax of if Statement

The basic syntax of an if statement is:

 
if (condition) {
// code to execute if the condition is true
}

Explanation:

  • condition: This is a Boolean expression that evaluates to true or false.

  • Curly braces {} are used to define the block of code that runs when the condition is true.

  • If the condition is false, the code inside the block is skipped.

Example 1: Simple if Statement

 
#include <iostream>
using namespace std;
int main() {
int number = 10;
if (number > 0) {
cout << "The number is positive." << endl;
}
return 0;
}

Output:

 
The number is positive.
  • The condition number > 0 is true, so the message is printed.

  • If number were -5, nothing would be printed because the condition would be false.

Example 2: if Statement with User Input

 
#include <iostream>
using namespace std;
int main() {
int age;
cout << "Enter your age: ";
cin >> age;
if (age >= 18) {
cout << "You are eligible to vote." << endl;
}
return 0;
}

Explanation:

  • The program checks the user’s input.

  • Only if age >= 18 is true, the message is displayed.

  • This is an example of real-life decision-making in programming.

Example 3: Using Relational Operators in if Statement

 
#include <iostream>
using namespace std;
int main() {
int marks;
cout << "Enter your marks: ";
cin >> marks;
if (marks >= 50) {
cout << "You passed the exam!" << endl;
}
return 0;
}
  • Here, the relational operator >= is used to check if marks are 50 or above.

Output (if marks = 60):

 
You passed the exam!

Output (if marks = 40):

 
  • Nothing is printed because the condition is false.

Tips for Using if Statements

  1. Always use relational or logical expressions in the condition.

  2. Curly braces {} are optional if there is only one statement, but it is recommended for clarity.

 
int a = 10;
if (a > 5)
cout << "a is greater than 5" << endl;
  • This works, but using {} is safer:

 
if (a > 5) {
cout << "a is greater than 5" << endl;
}
  1. Combine multiple conditions using logical operators:

 
int a = 20, b = 15;
if (a > 10 && b < 20) {
cout << "Both conditions are true." << endl;
}