Sometimes in your programs, you will need to perform checks inside other checks. These kind of conditional processing are called nested If statements or nested If-Else statements.
In common words, nesting is the process of placing a concept inside another concept. In our case, we are placing a conditional statement inside another conditional statement. The only thing you need to be careful about is the fact that every else clause corresponds to the nearest previous If clause. When dealing with nested conditional processing, you should always use code blocks as the body of the instructions, because nested conditional checks can be confusing. Here is an example of nested if statements:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
int hour = 7; int minute = 30; if (hour < 7) //first check if hour is less than 7 { Console.WriteLine("It is not morning yet"); } else //hour is greater than or equal to 7. Execute the nested condition checks! { if (minute < 30) //check if minute is less than 30 { Console.WriteLine("Wake up, shower, breakfast!"); } else //minute is greater than or equal to 30 { Console.WriteLine("Time to go to work!"); } } Console.Read(); |
The output follows:
The concepts explained in this lesson are also shown visually as part of the following video:
EXERCISES
1. Write a program that finds the biggest of three integers, using nested if
statements.
Solution
Guidelines: Use nested if
–statements, first checking the first two numbers then checking the bigger of them with the third.
2. Sort 3 real numbers in descending order. Use nested if
statements.
Solution
Guidelines: First find the smallest of the three numbers, and then swap it with the first one. Then check if the second is greater than the third number and if yes, swap them too.
Another approach is to check all possible orders of the numbers with a series of if-else
checks: a≤b≤c, a≤c≤b, b≤a≤c, b≤c≤a, c≤a≤b
and c≤b≤a
.
A more complicated and more general solution of this problem is to put the numbers in an array and use the Array.Sort(...)
method.
3. Write a program that finds the greatest of given 5 numbers.
Solution
Guidelines: Use nested if
statements.
Tags: conditional processing, if, if else, if else if else, if else instruction, nested if instructions
I am having an issue with my nested IF statement.
I am making a login with checking to see if the textbox is an empty string, also checking to see if it matches the correct user name and password.
Here is the code I have now, I have tried a few different things and have left it like this for now.
Any help is appreciated.
as far as i could see, there were only two wrong things with your code.. i tried to adapt it, but without knowing what it specifically does, thats all i can do.
Basically, you need to stop the execution of your codes as soon as you display an error message, otherwise the remainder of the code would execute. You do this using the C# keyword return