Nested if in C++
Last Updated :
06 Feb, 2023
If is a type of condition checking in which a condition turns out to be true a block of statements is executed.
Syntax:
// if base_condition is true
// every inside the { } block will be executed
if (base_condition)
{
statement 1...............
statement 2 ..............
}
Example
C++
#include <iostream>
using namespace std;
int main()
{
int a = 6, b = 5;
if (a > b) {
cout << "True" << endl;
}
}
|
What is Nested If?
When a number of if blocks are present one after another with the same scope (the same scope means under one { } block), then that condition is termed as a Nested if condition. If the first condition is True, we go into the next if condition and the subsequent condition is checked until we get a false condition, and the checking stops.
Syntax:
// if base_condition is true control goes to base_condition1
if ( base_condition)
{
// if base_condition is true control goes to base_condition2
if(base_condition1)
{
if(base_condition2)
..........................
..........................
}
}
Example 1:
C++
#include <iostream>
using namespace std;
int main()
{
int a = 20, b = 10, c = 2;
if (a > b) {
if (a > c) {
cout << " a is the largest " << endl;
}
}
return 0;
}
|
Example 2:
C++
#include <iostream>
using namespace std;
int main()
{
int a = 20, b = 10, c = 2;
if (a == 20) {
if (b == 10) {
if (c == 2) {
cout << "Sandeep Sir is Great!!" << endl;
}
}
}
return 0;
}
|
Output
Sandeep Sir is Great!!
Example 3:
C++
#include <iostream>
using namespace std;
int main()
{
int a = 20, b = 10, c = 1;
if (a == 20) {
if (b == 10) {
if (c == 2) {
cout << "Sandeep Sir is Great!!" << endl;
}
}
}
cout << "gfg\n" ;
return 0;
}
|
Example 4:
C++
#include <iostream>
using namespace std;
int main()
{
int a = 220, b = 10, c = 1;
if (a == 20) {
if (b == 10) {
if (c == 2) {
cout << "Sandeep Sir is Great!!" << endl;
}
}
}
cout << " No nested if condition is executed \n " ;
return 0;
}
|
Output
No nested if condition is executed
Time complexity: O(1).
Auxiliary space: O(1).
Share your thoughts in the comments
Please Login to comment...