C++ if-else statement
Introduction
In this post, we will discuss conditional execution using the if statement in C++ programs. C++ if statement in its simplest form and has the following syntax as below:
if(expression){
// statements to be executed when the expression is true
}
Flowchart
If the expression is true the action is executed, otherwise the action is not executed. Basic flowchart of the if statement is shown in the picture.

Sample Code
/*************************
* C++ if statement demo
*************************/
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "Please enter a number : " ;
cin >> n;
if(n > 0)
cout << "Number is positive." << endl;
return 0;
}
Sample run:
Please enter a number : 5
Number is positive.
Process returned 0 (0x0) execution time : 3.236 s
Press any key to continue.
*******************
Please enter a number : -5
Process returned 0 (0x0) execution time : 6.017 s
Press any key to continue.
*******************

if-else statement
In situations where different actions are to be executed based on the expression.
if(expression){
action1
}
else {
action2
}

/*************************
* C++ if statement demo
*************************/
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "Please enter a number : " ;
cin >> n;
// if-else statement
if(n > 0)
cout << "Number is positive." << endl;
else
cout << "Number is negative." << endl;
return 0;
}
Sample run
Please enter a number : 5
Number is positive.
Process returned 0 (0x0) execution time : 10.715 s
Press any key to continue.
**********************
Please enter a number : 5
Number is positive.
Process returned 0 (0x0) execution time : 10.715 s
Press any key to continue.
**********************
—
C++ Tutorials
C++ Tutorials on this website:
https://www.testingdocs.com/c-coding-tutorials/
For more information on the current ISO C++ standard