In this lesson, we will learn how to use the if..statement in C++ to write a decision-making program, with examples. In C++, there are three types of if…else statements. We will learn about the three different types in the next lessons.
The if statement is used in computer programming to run one piece of code under specific criteria and a different block of code under different ones.
Basic Syntax
if(condition){ // statements }
In the above syntax, the condition is a Boolean expression that returns True or False;
// Program checks if a number is even #include <iostream> using namespace std; int main() { int checkNumber; cout << "Please enter a number: "; cin >> checkNumber; if (checkNumber % 2 == 0) cout << checkNumber << " is an even number."; return 0; }
Output
Please enter a number: 4 4 is an even number.
The above program uses an if statement to decide whether or not 4 % 2 == 0
is true. The checkNumber
is even if this condition is true. If not, nothing will be displayed. So, the program will display “4 is an even number”.
This concludes the C++ if Statement lesson. The next lesson will teach you the if..else Statement in C++.