userNULL
userNULL

Reputation: 17

Using the switch statement instead of if

so I just started programming and I started with c#. In the book I'm reading (learning c# 3.0), one of the exercises was this.

Exercise 5-2. Create a program that prompts a user for input, accepts an integer, then evaluates whether that input is zero, odd or even, a multiple of 10, or too large (more than 100) by using multiple levels of if statements.

I managed to to this but the next exercise was

Exercise 5-3. Rewrite the program from Exercise 5-2 to do the same work with a switch statement.

I understand how switch statements work, but, I'm not sure how to work out if the user input number is odd/even, multiple of 10 and so on, and not use an if statement. Thank you for any help.

Upvotes: 1

Views: 1369

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 148980

You can do this:

int input = ...
switch (input)
{
    case 0:
        Console.WriteLine("Zero");
        default;
    default:
        switch (input < 100)
        {
            case true:
                switch (Math.Abs(input) % 10)
                {
                    case 0:
                        Console.WriteLine("Multiple of 10");
                        break;
                    case 2:
                    case 4:
                    case 6:
                    case 8:
                        Console.WriteLine("Even");
                        break;
                    default:
                        Console.WriteLine("Odd");
                        break;
                }
                break;
            default:
                Console.WriteLine("Too large");
                break;
        }
        break;
}

I don't think you can do this with a single switch in C#—unless you make it so massive as to account from every number from 0-100. You might be able to do it with a single Select statement in VB.NET, which is similar to a C# switch but has significantly different semantics.

Upvotes: 1

Related Questions