NESTED-IF- Statement:
It's also possible to nest one if statement inside another. (For that matter, it's
in general possible to nest any kind of statement or control flow construct
within another.) For example, here is a little piece of code which decides
roughly which quadrant of the compass you're walking into, based on an x value which is positive if you're walking east,
and a y value which is positive if
you're walking north:
if(x > 0)
{
if(y > 0)
printf("Northeast.\n");
else printf("Southeast.\n");
}
else {
if(y > 0)
printf("Northwest.\n");
else printf("Southwest.\n");
}
/* Illustates nested if else and multiple arguments to the scanf function. */
#include <stdio.h>
main()
{
int invalid_operator = 0;
char operator;
float number1, number2, result;
printf("Enter two numbers and an operator in the format\n");
printf(" number1 operator number2\n");
scanf("%f %c %f", &number1, &operator, &number2);
if(operator == '*')
result = number1 * number2;
else if(operator == '/')
result = number1 / number2;
else if(operator == '+')
result = number1 + number2;
else if(operator == '-')
result = number1 - number2;
else
invalid _ operator = 1;
if( invalid _ operator != 1 )
printf("%f %c %f is %f\n", number1, operator, number2, result );
else
printf("Invalid operator.\n");
}
Sample Program Output
Enter two numbers and an operator in the format
number1 operator number2
23.2 + 12
23.2 + 12 is 35.2