C++ Nested If statement – All you need to know!

Filed Under: C++
C NESTED IF STATEMENT

Hey, all. In this article, we will focus on C++ Nested If statement.

C++ programming language contains various selection and iteration statements to work with the data values in an efficient manner.

In order to work with the complex data manipulation, we have Nested if statement.

So, let us begin!


What is Nested If Statement in C++?

C++ If statement enables us to work with conditions on the data as shown below:

Syntax: IF statement

if(condition)
{
//body
}

So, to relate with, Nested If statement is an IF statement within another set of IF statements. Thus, it makes us consider one IF statement as the target value of another IF statement.

That is, the condition of an if statement would invoke action of another if statement. This is the working factor of Nested If statements.

Having understood the working of Nested IF statements, let us now focus on the structure of the same in the upcoming section.


Syntax of Nested IF statement

Let us have a look at the below syntax–

if (condition_1)  // first if statement
{
   
   if (condition_2) // second if statement
   {
      //body
   }
   if (condition_N) // third if statement
   {
      // body
   }
 //body
}

As seen above, the first if statement works only when the condition_1 is true. Further, the second and third if statements are the target values of the first if statement and follow the nested if format.

Now, let us try implementing this syntax through the below examples.


Example of Nested If statement in C++

Let us have a look at the below example of nested if statement–

#include <iostream> 
using namespace std; 

int main() 
{ 
	int x = 100; 
    int z = 20;
	if (x > 10) 
	{ 
		if (z>10) 
		cout<<"Both x and z are greater than 10\n"; 
		
                if (z % 3 == 0) 
			cout<<"Z is a multiple of 2\n"; 
		else if (z % 5 == 0)
			cout<<"Z is a multiple of 5\n"; 
		else
		cout<<"Error!!";
          }
	return 0; 
} 

In the above example, if the first condition i.e. x>10 is true, then only the code execution gets into the statement. Further, it executes the other nested if statements based on the conditions and returns the value.

Output:

Both x and z are greater than 10
Z is a multiple of 5

Conclusion

By this, we have come to the end of this topic. Feel free to comment below, in case you come across any question.

For more such posts related to C++, do visit C++ Programming with JournalDev.


References

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages