Friday, July 04, 2025 10:01

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:

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:

nested if statements

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 ifstatements, first checking the first two numbers then checking the bigger of them with the third.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter first number: ");
            int a = Int32.Parse(Console.ReadLine());
            Console.Write("Enter second number: ");
            int b = Int32.Parse(Console.ReadLine());
            Console.Write("Enter third number: ");
            int c = Int32.Parse(Console.ReadLine());

            if (a > b)
            {
                if (a > c) Console.WriteLine("A is the biggest");
                else if (a < c) Console.WriteLine("C is the biggest");
                else Console.WriteLine("A and C are the biggest");
            }
            else if (a < b) { if (b > c) Console.WriteLine("B is the biggest");
                else if (b < c) Console.WriteLine("C is the biggest");
                else Console.WriteLine("B and C are the biggest");
            }
            else if (a == b)
            {
                if (a == c) Console.WriteLine("All are equal");
                else if (a < c) Console.WriteLine("C is the biggest");
                else Console.WriteLine("A and B are the biggest");
            }
        }
    }
}

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.

using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter first number: ");
            int a = Int32.Parse(Console.ReadLine());
            Console.Write("Enter second number: ");
            int b = Int32.Parse(Console.ReadLine());
            Console.Write("Enter third number: ");
            int c = Int32.Parse(Console.ReadLine());

            if (a < b)
            {
                if (a < c) 
                { 
                    a = a + c; 
                    c = a - c; 
                    a = a - c; 
                    if (b > c)
                    {                        
                        a = a + b;
                        b = a - b;
                        a = a - b;
                    }
                }
                else if (a >= c)
                {
                    a = a + b;
                    b = a - b;
                    a = a - b;
                }
            }
            else if (a == b)
            {
                if (a < c)
                {
                    a = a + c;
                    c = a - c;
                    a = a - c;
                }
            }
            else
            {
                if (b < c)
                {
                    b = b + c;
                    c = b - c;
                    b = b - c;
                }
                if (a < b)
                {
                    a = a + b;
                    b = a - b;
                    a = a - b;
                }
            }
            Console.WriteLine("{0}, {1}, {2}", a, b, c);
            Console.ReadLine();
        }
    }
}

3. Write a program that finds the greatest of given 5 numbers.

Solution


Guidelines: Use nested if statements.

static void Main(string[] args)
{    
    Console.Write("Enter first number: ");
    int a = Int32.Parse(Console.ReadLine());
    Console.Write("Enter second number: ");
    int b = Int32.Parse(Console.ReadLine());
    Console.Write("Enter third number: ");
    int c = Int32.Parse(Console.ReadLine());
    Console.Write("Enter fourth number: ");
    int d = Int32.Parse(Console.ReadLine());
    Console.Write("Enter fifth number: ");
    int e = Int32.Parse(Console.ReadLine());
    
    if (a < b) a = b;
    if (a < c) a = c;
    if (a < d) a = d;
    if (a < e) a = e;
    
    Console.WriteLine("{0} is the biggest number.", a);
}

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.

    
    private void btnLogin_Click(object sender, EventArgs e)
    {
        if (txtUserName.Text.Trim() == string.Empty)
        {
            MessageBox.Show(“Please insert user name ” + ” User name can not be blank”);
            txtUserName.Clear();
            txtUserName.Focus();
        }
    
        // con.Open();
        cmd = new SqlCommand(“Select * FROM Users WHERE UserName = '” + txtUserName.Text.Trim() + 
        “‘Collate SQL_LATIN1_General_Cp1_CS_AS”, con);
        sda = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();
        sda.Fill(dt);
        if (dt.Rows.Count == 1)
        {
            // MainDataBase mdb = new MainDataBase();
            // this.Hide();
            // mdb.Show();
        }
        else
        {
            MessageBox.Show(“Wrong user name”);
            txtUserName.Clear();
            txtUserName.Focus();
            con.Close();
        }
    
        if (txtUserName.Text.Trim() == string.Empty)
        {
            MessageBox.Show(“Please insert password ” + ” Password can not be blank”);
            txtUserName.Clear();
            txtUserName.Focus();
        }
    
        cmd = new SqlCommand(“Select Role FROM Users WHERE Pass = '” + txtPassword.Text.Trim() + 
        “‘Collate SQL_LATIN1_General_Cp1_CS_AS”, con);
        sda = new SqlDataAdapter(cmd);
        //DataSet ds = new DataSet();
        //DataTable dt = new DataTable();
        sda.Fill(dt);
        if (dt.Rows.Count == 1)
        {
    
            MainDataBase mdb = new MainDataBase();
            this.Hide();
            mdb.Show();
        }
    
        else
        {
            MessageBox.Show(“Wrong password”);
            txtPassword.Clear();
            txtPassword.Focus();
            con.Close();
        }
    }
    

    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.

      private void btnLogin_Click(object sender, EventArgs e)
      {
          //string.Empty assumes there is nothing there, not even white space, so no need to trim
          if (txtUserName.Text != string.Empty)
          {
              MessageBox.Show(“Please insert user name ” + ” User name can not be blank”);
              txtUserName.Clear();
              txtUserName.Focus();
              return; //make sure to skip the remaining code
          }
      
          // con.Open();
          cmd = new SqlCommand(“Select * FROM Users WHERE UserName = '” + txtUserName.Text.Trim() + “‘Collate SQL_LATIN1_General_Cp1_CS_AS”, con);
          sda = new SqlDataAdapter(cmd);
          DataSet ds = new DataSet();
          DataTable dt = new DataTable();
          sda.Fill(dt);
          if (dt.Rows.Count == 1)
          {
              // MainDataBase mdb = new MainDataBase();
              // this.Hide();
              // mdb.Show();
          }
          else
          {
              MessageBox.Show(“Wrong user name”);
              txtUserName.Clear();
              txtUserName.Focus();
              con.Close();
              return;
          }
      
          if (txtUserName.Text != string.Empty)
          {
              MessageBox.Show(“Please insert password ” + ” Password can not be blank”);
              txtUserName.Clear();
              txtUserName.Focus();
              return;
          }
      
          cmd = new SqlCommand(“Select Role FROM Users WHERE Pass = '” + txtPassword.Text.Trim() + “‘Collate SQL_LATIN1_General_Cp1_CS_AS”, con);
          sda = new SqlDataAdapter(cmd);
          //DataSet ds = new DataSet();
          //DataTable dt = new DataTable();
          sda.Fill(dt);
          if (dt.Rows.Count == 1)
          {
              //also close db connection here
              MainDataBase mdb = new MainDataBase();
              this.Hide();
              mdb.Show();
          }
          else
          {
              MessageBox.Show(“Wrong password”);
              txtPassword.Clear();
              txtPassword.Focus();
              con.Close();
          }
      }
      

      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 to Robert