C++ If... Else and Nested If... Else
C++ If... Else and Nested If... Else
com
Contents
if Statement
if...else Statement
Nested if...else Statement
Conditional Operator
Working of if Statement
ASHISH PRAJAPATI 1
Ashishprajapati29.wordpress.com
false, the codes inside curly bracket { } is skipped and control of program goes just
below the body of if as shown in figure above.
Flowchart of if
#include <iostream>
using namespace std;
int main() {
int number;
cout<< "Enter an integer: ";
cin>> number;
ASHISH PRAJAPATI 2
Ashishprajapati29.wordpress.com
}
Output 1
Enter an integer: 5
Output 2
Enter a number: -5
The if...else executes body of if when the test expression is true and executes the
body of elseif test expression is false.
ASHISH PRAJAPATI 3
Ashishprajapati29.wordpress.com
The if statement checks whether the test expression is true or not. If the test
condition is true, it executes the code/s inside the body of if statement. But it the
test condition is false, it executes the code/s inside the body of else.
Flowchart of if...else
#include <iostream>
using namespace std;
int main() {
int number;
cout<< "Enter an integer: ";
cin>> number;
if ( number >= 0) {
cout << "You entered a positive integer: "<<number<<endl;
ASHISH PRAJAPATI 4
Ashishprajapati29.wordpress.com
else {
cout<<"You entered a negative integer: "<<number<<endl;
}
}
Output
Enter an integer: -4
if (test expression1){
ASHISH PRAJAPATI 5
Ashishprajapati29.wordpress.com
else {
The nested if...else statement has more than one test expression. If the first test
expression is true, it executes the code inside the braces { } just below it. But if the
first test expression is false, it checks the second test expression. If the second test
expression is true, if executes the code inside the braces { } just below it. This
process continues. If all the test expression are false, code/s inside else is executed
and the control of program jumps below the nested if...else
#include <iostream>
using namespace std;
int main() {
int number;
cout<< "Enter an integer: ";
cin>> number;
if ( number > 0) {
cout << "You entered a positive integer: "<<number<<endl;
}
else if (number < 0){
cout<<"You entered a negative integer: "<<number<<endl;
}
else {
cout<<"You entered 0."<<endl;
}
ASHISH PRAJAPATI 6
Ashishprajapati29.wordpress.com
}
Output
Enter an integer: 0
You entered 0.
This statement is always executed because it's outside nested if...else statement.
if ( a < b ) {
a = b;
else {
a = -b;
a = (a < b) ? b : -b;
Both codes above check whether a is less than b or not. If a is less than b, value
of b is assigned to a if not, -b is assigned to a.
ASHISH PRAJAPATI 7