How to use the if statement in C++
Overview
The if statement in C++ is used to specify a block of code that will be executed if a condition provided is true.
Syntax
if (condition){
statement
}
The statement or command will execute provided the given condition is true.
Example
Let’s write a code using the if statement:
#include <iostream>using namespace std;int main() {// creating a conditionif (2 > 1) {// creating a statement/block of code to be executedcout << "2 is greater than 1";}return 0;}
Explanation
- Line 6: We use the
ifstatement. We create a condition, if the number2is greater than1, the block of code or statement in line 9 should be executed. - Line 9: we create a statement or block of code to be executed provided that the condition in line 6 is
true.
We can also use the if statement to test variables.
Example
#include <iostream>using namespace std;int main() {// creating variablesint x = 1;int y = 2;// creating conditionif (x < y) {// statement/block of code to be executedcout << "x is less than y";}return 0;}
Explanation
-
Line 6 and 7: We create integer variables
xandy. -
Line 10: We compare the values of
xandy. Ifyis greater thanxthen the condition istrue. -
Line 13: We create a statement or block of code to execute provided the condition given in line 10 is
true.