Menu
Coddy logo textTech

Nested If - Else

Part of the Fundamentals section of Coddy's C# journey — lesson 30 of 69.

We can nest if-elif-else statements within each other. This allows us to create hierarchical decision-making structures.

For example:

if (age > 18) {
    if (hasLicense) {
        Console.WriteLine("You can drive");
    } else {
        Console.WriteLine("Get a license first");
    }
} else {
    Console.WriteLine("Too young to drive");
}

It can be infinite nested:

if (condition1) {
	if (condition2) {
		if (condition3) {
		    // if condition1, condition2 and condition3 are true
		    ...
		}
	}
}
challenge icon

Challenge

Beginner

Create a program that checks if someone can ride a rollercoaster. The requirements are:

  • Must be at least 12 years old
  • Must be taller than 150cm
  • If they meet both requirements but are under 15, they need adult supervision

Set status variable to exactly these string for each case:

  • If too young: Sorry, you're too young
  • If not tall enough: Sorry, you're not tall enough
  • If under 15 and no adult: Sorry, you need an adult with you
  • If under 15 with adult: You can ride with adult supervision!
  • If 15 or older and tall enough: You can ride by yourself!

Cheat sheet

You can nest if-elif-else statements within each other to create hierarchical decision-making structures:

if (age > 18) {
    if (hasLicense) {
        Console.WriteLine("You can drive");
    } else {
        Console.WriteLine("Get a license first");
    }
} else {
    Console.WriteLine("Too young to drive");
}

Nesting can be done infinitely:

if (condition1) {
    if (condition2) {
        if (condition3) {
            // if condition1, condition2 and condition3 are true
            ...
        }
    }
}

Try it yourself

using System;

class Program {
    public static void Main(string[] args) {
        int age = int.Parse(Console.ReadLine()); // Don't change this line
        int height = int.Parse(Console.ReadLine()); // Don't change this line
        bool hasAdult = bool.Parse(Console.ReadLine()); // Don't change this line

        string status = "";
        
        // Write your code below
        
        
        
        // Don't change below this line
        Console.WriteLine(status);
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals