0
0
C Sharp (C#)programming~5 mins

Nested conditional execution in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Nested conditional execution helps you make decisions inside other decisions. It lets your program check more than one condition step by step.

When you want to check if a number is positive, negative, or zero.
When you need to decide a grade based on score ranges.
When you want to check user input and then check more details about it.
When you want to handle different cases inside a main choice.
When you want to check multiple related conditions in order.
Syntax
C Sharp (C#)
if (condition1)
{
    if (condition2)
    {
        // code if both condition1 and condition2 are true
    }
    else
    {
        // code if condition1 is true but condition2 is false
    }
}
else
{
    // code if condition1 is false
}

You can put one if statement inside another to check more conditions.

Use braces { } to keep your code clear and avoid mistakes.

Examples
This checks if a number is positive and less than 20.
C Sharp (C#)
int number = 10;
if (number > 0)
{
    if (number < 20)
    {
        Console.WriteLine("Number is between 1 and 19");
    }
}
This decides a grade based on score using nested conditions.
C Sharp (C#)
int score = 85;
if (score >= 60)
{
    if (score >= 90)
    {
        Console.WriteLine("Grade A");
    }
    else
    {
        Console.WriteLine("Grade B");
    }
}
else
{
    Console.WriteLine("Fail");
}
Sample Program

This program asks for your age and tells you if you are a minor, an adult, or a senior adult using nested if statements.

C Sharp (C#)
using System;

class Program
{
    static void Main()
    {
        Console.Write("Enter your age: ");
        int age = int.Parse(Console.ReadLine() ?? "0");

        if (age >= 18)
        {
            if (age >= 65)
            {
                Console.WriteLine("You are a senior adult.");
            }
            else
            {
                Console.WriteLine("You are an adult.");
            }
        }
        else
        {
            Console.WriteLine("You are a minor.");
        }
    }
}
OutputSuccess
Important Notes

Always test your nested conditions with different inputs to make sure they work as expected.

Too many nested conditions can make code hard to read. Keep it simple or use other ways if it gets complicated.

Summary

Nested conditional execution lets you check one condition inside another.

It helps make decisions that depend on multiple steps.

Use clear braces and test your code well.