The if
statement in C++ is used to specify a block of code that will be executed if a condition provided is true
.
if (condition){
statement
}
The statement
or command will execute provided the given condition
is true
.
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;}
if
statement. We create a condition, if the number 2
is greater than 1
, the block of code or statement in line 9 should be executed.true
.We can also use the if
statement to test variables.
#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;}
Line 6 and 7: We create integer variables x
and y
.
Line 10: We compare the values of x
and y
. If y
is greater than x
then the condition is true
.
Line 13: We create a statement or block of code to execute provided the condition given in line 10 is true
.