Sunday, June 23, 2024 21:33

Table of contents >> Introduction > Nested If statements

Nested If statements

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:

The output follows:

nested if statements

The concepts explained in this lesson are also shown visually as part of the following video:


1. Write a program that finds the biggest of three integers, using nested if statements.


Guidelines: Use nested ifstatements, 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.


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.


Guidelines: Use nested if statements.

Tags: , , , , ,

2 Responses to “Nested If statements”

  1. Robert says:

    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.

    • rusoaica says:

      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

Leave a Reply

Follow the white rabbit