C++ 08: Nested If-else
Nested if-else
Sometimes, we need to use an if statement inside another if statement. This is known as nested if statement.
Think of it as multiple layers of if statements. There is a first, outer if statement, and inside it is another, inner if statement. Its syntax is:
// outer if statement
if (condition1) {
// statements
// inner if statement
if (condition2) {
// statements
}
}Examples on nested if
#include <iostream>
using namespace std;main(){ int n; int a, b, c; int p, q, r;
cout << "Enter a number: "; cin >> n;
if (n > 0) { if (n % 2 == 0) { cout << n << " is a Positive Even Number"; } else { cout << "Invalid Number.It is Odd Number!"; } } else { cout << "Invalid Number.It is Negative Number!"; } return 0;}Output:
Enter a number: 45
Invalid Number. It is Odd Number!2.WAP to check that triangles can be formed or not and then check that equilateral or right andle tri
#include <iostream>
using namespace std;main(){ cout << "Enter Three angles :"; cin >> a >> b >> c;
if (a + b + c == 180) { cout << "Triangle can be Formed"; if (a == b && a == c && c == b) { cout << "Formed triangle is Equilateral Triangle"; } else if (a == 90 || b == 90 || c == 90) { cout << "It is Right angled triangle"; } else { cout << "It is neither equilateral triangle nor right angle triangle"; } } else { cout << "Triangle cannot be formed"; } return 0;}Output
Enter Three angles :30 60 90
Triangle can be Formed It is Right angled triangle3.WAP to find greatest of three numbers.
#include <iostream>
using namespace std;main(){ //Greatest of three number cout << "Enter three Numbers: "; cin >> p >> q >> r;
if (a > b && a > c) { cout << "A is Greatest" << p; } else if (b > c) { cout << "Greatest is " << q; } else { cout << "Greatest is " << r; } return 0;}Output
Enter three Numbers: 8 7 9
Greatest is 9
Comments
Post a Comment