C++ if, if...else and Nested if...else
In this topic, we will learn about the if...else statement to create decision
making programs with the help of examples.
In computer programming, we use the if...else statement to run one block of
code under certain conditions and another block of code under different
conditions.
For example, assigning grades (A, B, C) based on marks obtained by a
student.
• if the percentage is above 90, assign grade A
• if the percentage is above 75, assign grade B
• if the percentage is above 65, assign grade C
There are three forms of if...else statements in C++.
1. if statement
2. if...else statement
3. if...else if...else statement
C++ if Statement
The syntax of the if statement is:
if (condition) {
// body of if statement
, ELITE TUTORING
}
The if statement evaluates the condition inside the parentheses ( ).
• If the condition evaluates to true , the code inside the body of if is
executed.
• If the condition evaluates to false , the code inside the body of if is
skipped.
Note: The code inside { } is the body of the if statement.
How if Statement Works
Example 1: C++ if Statement
// Program to print positive number entered by the user
// If the user enters a negative number, it is skipped
#include <iostream>
using namespace std;
int main() {