A nested if-else statement in C programming is an if statement that is another if-else statement inside it. And Inside else statement also another if-else statement present. Yes, both C and C++ allow us to nested if-else statements within if statements if-else, that is, we can place an if-else statement inside another else statement.
A program to check whether a number is positive, negative or zero. If positive to check whether the number is odd or even, demonstrate the use of nested if-else.
#include<stdio.h>//header file for standard input and output int main()//main function initialised as integer {//main function braces opened int num;//variable number initialised as integer to take user input printf("Enter the number you want to check");//print message scanf("%d",&num);//user input if(num>0)//test case to check if number is greater than 0 {//if braces opened printf("\nThe number is positive");//positive message if(num%2==0)//test case to check even or odd printf("\nThe number is even");//print message else//else case (if not satisfied) printf("\nThe number is odd");//print message }//if braces closed else if(num==0)//else if case where number is equal to zero {//braces opened printf("\nThe number is equals to zero");//print message }//braces closed else//else case if above cases not satisfied {//braces opened printf("\nThe number is negative");//print message }//braces closed return 0;//execution success }//main function braces closed
Explanation Of whether a number is positive, negative or zero. If positive to check whether the number is odd or even:
- Header file for standard input and output.
- The main function initialised as an integer.
- The main function braces opened.
- The variable number initialised as integer to take user input.
- print message on a console for input purposes.
- user input through scanf().
- test case to check if a number is greater than 0.
- if braces opened.
- positive message.
- test case to check even or odd.
- print message if even.
- print message if odd.
- nested if braces closed.
- else if the case where number is equal to zero.
- braces opened In else-if after successful check if the number is zero.
- print message the number is zero.
- braces closed In else-if after successful check if the number is zero.
- else case if above cases, not satisfied.
- braces opened if all the cases are false.
- print message the number is negative.
- braces closed if all the cases are false.
- execution success.
- main function braces close.
This was an example of nested if….else decision making in C, hope you like it and have cleared your doubts.
Please write comments or WhatsApp if you find anything incorrect, or you want to share more information about the topic discussed above.