What is if Statement in C++?
The if statement in C++ is used to check a condition. If the condition is true, the code inside the if block is executed. If the condition is false, the code is skipped.
It is one of the most important decision-making statements in C++.
Syntax of if Statement:
if (condition) {
// code to be executed
}
How if Statement Works
- First, the condition is evaluated inside parentheses.
- If it is true, the code inside if executes.
- If it is false, the program moves to the next statement.
Example
#include <iostream>
using namespace std;
int main() {
int number = 10;
if (number > 0) {
cout << "Positive number";
}
return 0;
}
Output:
Positive number
Explanation:
- The condition number > 0 is checked.
- Since 10 is greater than 0, the condition is true.
- So, the message is printed.
Summary:
- if statement is used for decision making.
- It executes code only when the condition is true.
- If the condition is false, the code is skipped.
- It is the simplest control statement in C++.