C++ Nested if-else statements
In C++, a nested if-else statement is a combination of multiple if-else statements that are nested inside one another. This type of statement is used when multiple conditions need to be checked in a specific order.
Syntax of nested if-else statement:
if (condition1) {
// code block to execute if condition1 is true
if (condition2) {
// code block to execute if both condition1 and condition2 are true
}
else {
// code block to execute if condition1 is true but condition2 is false
}
}
else {
// code block to execute if condition1 is false
}
Example of a nested if-else statement
#include <iostream>
using namespace std;
int main() {
int num1, num2;
cout << "Enter two numbers: ";
cin >> num1 >> num2;
if (num1 > 0) {
if (num2 > 0) {
cout << "Both numbers are positive" << endl;
}
else {
cout << "First number is positive but second number is not" << endl;
}
}
else {
cout << "First number is not positive" << endl;
}
return 0;
}
Output:
Enter two numbers: 3 -4
First number is positive but second number is not
Here, we ask the user to enter two integers before determining whether the first one is positive. If so, we then determine whether the second number is also positive. If so, a message stating that both numbers are positive is printed. If not, a message stating that the first number is positive but the second number is not is printed. We print a message indicating that the first number is not positive if it is not positive.
Another Example:
#include <iostream>
using namespace std;
int main() {
int age, salary;
cout << "Enter your age: ";
cin >> age;
if (age >= 18) {
cout << "Enter your salary: ";
cin >> salary;
if (salary >= 50000) {
cout << "Congratulations! You are eligible for a credit card." << endl;
}
else {
cout << "Sorry, you are not eligible for a credit card as your salary is below the minimum requirement." << endl;
}
}
else {
cout << "Sorry, you are not eligible for a credit card as you are below 18 years of age." << endl;
}
return 0;
}
Output:
Enter your age: 22
Enter your salary: 60000
Congratulations! You are eligible for a credit card.