The if-else
statement in C++ is used to build a program that can make decisions based on certain conditions.
The if-else
statement consists of:
if
statementelse
statementThey both (if
and else
) combine to execute a block of code or work together to execute statements based on a logical expression.
The following flowchart depicts how the if-else
statement works:
if
statementThe if
statement specifies a block of code that needs to be executed, if the given condition is True
.
if (condition){
statement(s)
}
The statement
or block of code that needs to be executed in the code syntax given above will execute only if the given condition
is True
.
The following code demonstrates the use of the if
statement:
#include <iostream>using namespace std;int main() {int x = 2;if (x > 1) {cout << "x is greater than 1";}else {cout <<"x is less than or equal to 1";}return 0;}
if
statement.True
.if-else
statementThe if-else
statement contains two blocks of statements (the if
and else
statements) and executes them based on a logical expression.
if (condition) {
statement_1(s);
} else {
statement_2(s);
}
The code given above will execute statement_1
in the if
block,
only if the condition
is True
. If the condition
is False
, then the code will execute statement_2
in the else
block.
The following code demonstrates the use of the if-else
statement:
#include <iostream>using namespace std;int main() {int x = 2;if (x > 1) {cout << "x is greater than 1";}else {cout <<"x is less than or equal to 1";}return 0;}
if
statement.True
.else
statement, which executes if the condition provided in line 6 is False
.else
block, if the given condition in line 6 is False
.RELATED TAGS
CONTRIBUTOR