Trusted answers to developer questions

What is the if-else statement in C++?

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

Overview

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:

  • An if statement
  • An else statement

They 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:

Flowchart of the "if-else" statement

if statement

The if statement specifies a block of code that needs to be executed, if the given condition is True.

Syntax

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.

Code

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;
}

Code explanation

  • Line 6: We create a condition, using the if statement.
  • Line 7: We create a statement or block of code that is executed, if the condition in line 6 is True.

if-else statement

The if-else statement contains two blocks of statements (the if and else statements) and executes them based on a logical expression.

Syntax

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.

Code

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;
}

Code explanation

  • Line 6: We give a condition, using the if statement.
  • Line 7: We create a block of code or statement that is executed, if the condition in line 6 is True.
  • Line 9: We use the else statement, which executes if the condition provided in line 6 is False.
  • Line 10: We create a block of code that is executed for the else block, if the given condition in line 6 is False.

RELATED TAGS

control flow
c++

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
Did you find this helpful?