Nested if refers to an If statement within another if statement. Is shouldn’t be mixed with multiple if statements where a program contains more than one if condition. Nested if statement first checks the outermost condition to see whether it is true, then proceeds to the inner if condition. If the outermost condition is false the program will skip all the inner conditions and will directly process the else part. Lets first compare it with multiple if
If (x>0)
printf(“\nX is a positive number”);
else
printf(“X is a negative number”);
If(x%2==0)
printf(“\nX is an even number”);
else
printf(“\nX is an odd number”);
The above program will process the second if irrespective of whether the first condition was true or not. Which means that if we enter X as 10, the first if evaluate to true since it is a positive number. The second if will also result in true since x is an even number and dividing it by 2 will yield 0. Note that since both the conditions are different the second condition will be processed even if the first condition evaluates to false. Now compare it with nested if :
If (x>0)
{
printf(“\nX is a positive number”);
if(x%2==0)
printf(“\nX is an even number”);
else
printf(“\nX is an odd number”);
}
else
printf(“X is a negative number”);
The above program is an example of nested if because the second if statement starts and ends within the first if condition. So if we enter a negative value the first condition will become false and the program will jump to the else part and will print “X is a negative number” without checking the inner condition.
Here’s is the syntax
if(outercondition)
{
if(innercondition)
Statements if innercondition is true
else
Statements if innercondition is false
}
else
statements if outercondition is false
Example 2:
Lets write a program that will check the username and password of a user and prints the appropriate error message.
void main()
{
char name,pass; //single char username and password
printf(“\nEnter username : “);
scanf(“%c”,&name);
printf(“\nEnter password : “);
scanf(“%c”,&pass);
if(uname==’A’)
{
if(pass==’$’)
printf(“\nUsername and password are valid. You can login”);
else
printf(“\nInvalid Password”);
}
else
printf(“\nInvalid username”);
Output (If both inputs are correct)
Enter username : A
Enter password : $
Username and password are valid. You can login
Output (If password is incorrect)
Enter username : A
Enter password : %
Invalid Password
Output (If username is incorrect)
Enter username : G
Enter password : $
Invalid username
0 comments:
Post a Comment