Day 3: Conditionals (If, Else, Switch)
T
Tuan Beo

Day 3: Conditionals (If, Else, Switch)

Learn how to make your program decide what to do based on conditions.

๐Ÿ“ Theory (Details)

  • If Statement: Runs code only if a condition is true.

    if (age >= 18)
    {
        Console.WriteLine("You are an adult.");
    }
    else
    {
        Console.WriteLine("You are not an adult.");
    }
    
  • Comparison Operators:

    • == equal

    • != not equal

    • > greater than

    • < less than

    • >= greater or equal

    • <= less or equal

  • Logical Operators:

    • && (AND)

    • || (OR)

    • ! (NOT)

  • Switch Statement: Cleaner way for multiple options.

    switch (dayOfWeek)
    {
        case 1: Console.WriteLine("Monday"); break;
        case 2: Console.WriteLine("Tuesday"); break;
        default: Console.WriteLine("Other day"); break;
    }
    

๐Ÿ’ป Practice

Step 1 โ€“ Simple If/Else

Console.Write("Enter your age: ");
int age = Convert.ToInt32(Console.ReadLine());

if (age >= 18)
{
    Console.WriteLine("You are an adult.");
}
else
{
    Console.WriteLine("You are not an adult.");
}

Step 2 โ€“ If/Else If Chain

Console.Write("Enter your score (0โ€“100): ");
int score = Convert.ToInt32(Console.ReadLine());

if (score >= 90)
    Console.WriteLine("Grade: A");
else if (score >= 75)
    Console.WriteLine("Grade: B");
else if (score >= 50)
    Console.WriteLine("Grade: C");
else
    Console.WriteLine("Grade: F");

Step 3 โ€“ Switch Example

Console.Write("Enter a number 1โ€“3: ");
int option = Convert.ToInt32(Console.ReadLine());

switch (option)
{
    case 1: Console.WriteLine("Option One Selected"); break;
    case 2: Console.WriteLine("Option Two Selected"); break;
    case 3: Console.WriteLine("Option Three Selected"); break;
    default: Console.WriteLine("Invalid Option"); break;
}

Step 4 โ€“ Mini Exercise ๐ŸŽฏ

Write a program that asks the user to enter a number.

  • If divisible by 3 โ†’ print "Fizz"

  • If divisible by 5 โ†’ print "Buzz"

  • If divisible by both 3 and 5 โ†’ print "FizzBuzz"

  • Otherwise print the number itself.

Comments