codeasy .net
or Sign Up
C# Beginner > 6 The truth > Switch statement

Tired while learning c sharp

You Forgot One Thing

Helping Noname one more time (again) was starting to wear on me. As was beginning to happen too often, the minute I thought I was free to get a little rest, someone else had other plans. Sara cornered me just as I was opening the door to my room.

"Hi, Teo! I heard that you were chosen for the Rust project? Congratulations!" Sara said.
"Thanks Sara," I said, " but can we talk another time? I need to rest..."
"Oh, sure," she said sarcastically, "I didn't realize you wanted to fail your exam. What do you think is more important: sleep, or passing the exam and getting a ticket to Wonderland?"

Of course, another set of tasks or lessons to be had. Endless work around the base. To be honest, all I was looking forward to was Noname sending me back to my normal life. But I knew how to play my role, and I replied "I hope this thing you want to tell me is really that important." I answered.

"It is. In short: we fed a code analyzer all the code that you have written so far, and it determined that you have never used a switch statement," Sara explained.
"Of course I've never used a switch statement, I don't even know what it is!"
"You'd better learn it! At the exam, Infinity can (and often does) ask about it!"
"Ok, let me just take some coffee. Then I learn about switch statements, and everyone leaves me alone so I can get some sleep."

Multiple Choices

"Let's start with a simple program where the user inputs questions to the console," Sara started. "The program should do the following:

  1. Answer with "I love you!" when the user asks "Do you love me?"
  2. Answer with "You look awesome!" when the user asks "How do I look today?"
  3. Answer "I have no clue what you are talking about." when the user prints something else.

Can you write this program for me?"
Despite my distinct lack of sleep, I managed to write it in one minute flat.

var question = Console.ReadLine();

if (question == "Do you love me?")
{
    Console.WriteLine("I love you!");
}
else if (question == "How do I look today?")
{
    Console.WriteLine("You look awesome!");
}
else
{
    Console.WriteLine("I have no clue what you are talking about.");
}

"Great, Teo! As you know, an if statement is used when you have two logical choices and your program needs to choose between them. In this case, you have three logical choices, and because of that, you had to use if several times. You can probably guess where this is going - this is why the switch statement was invented. The switch statement is used to perform different actions based on different conditions. Here's what your code looks like when we use the switch statement instead of an if:"

var question = Console.ReadLine();

switch (question)
{
    case "Do you love me?":
        Console.WriteLine("I love you!");
        break;
    case "How do I look today?":
        Console.WriteLine("You look awesome!");
        break;
    default:
        Console.WriteLine("I have no clue what you are talking about.");
        break;
}

The most important c# concept

"I guess this was important enough to keep me out of bed a bit longer!" I said. "Why hasn't anyone told me about switch statements before now?" I asked.
"To be honest, Teo, we purposely wanted you to NOT learn the most powerful aspects of C# because we didn't trust you. But then you started learning things outside the base, like the if statement from that guy from the C gang, and we didn't have much of a choice."
"Thanks, I suppose," I said.
"Now back to the switch statement. Here is its general form:"

switch (someValue)
{
    case value1:
        // Execution goes here if someValue == value1
        break;
    case value2:
        // Execution goes here if someValue == value2
        break;
    default:
        // Execution goes here if someValue is different from all the
           options above
        break;
}

"How does it work exactly, Sara?" I asked.
"First, someValue is calculated. Then, it's compared with each of the case values. If there's a match, the associated block of code is executed. If there is no match, the default block is executed."
"Okay," I replied, "That seems easy enough. What does break mean?"
"break is used to indicate that the program should stop checking different case options and break, or exit, out of the switch statement. Here is your first task using a switch statement."

Write a program that reads the user's name from the console first. Then, according to the name, it performs one of three actions:

  1. If the name is "admin", the program should print "Welcome! Full access granted."
  2. If the name is "user", the program should print "Welcome! Limited access granted."
  3. If the name is not "user" or "admin", the program should print "Unknown user."

Use a switch statement in your solution. For example:
>admin
Welcome! Full access granted.

"Good work!" Sara said.
"Yeah, this isn't that hard, actually," I answered.

"Ok then, let's go to something a bit harder. First of all, there can be more than one line of code in every case block. Second, the type of variable that you check in a switch doesn't have to be a string; it could be, for instance, an int. Here's a more complicated example."

int errorCode = int.Parse(Console.ReadLine());
switch (errorCode)
{
    case 0:
        Console.WriteLine("Don't worry, everything is fine.");
        break;
    case 1:
        Console.WriteLine("Unrecognised object detected!");
        TerminateObject();
        SendEmailToAdmin();
        break;
    case 2:
        Console.WriteLine("Transfunction module update needed.");
        UpdateTransfunctionModule();
        break;
    default:
        Console.WriteLine("Unknown error code.");
        break;
}

"One more useful thing to know: the default can be omitted (the same as else in the if statement)," Sara added.

We like ciphers at the resistance base. For internal communication, we use a substitutional cipher. The idea is very simple: every letter in the incoming message is substituted with a different symbol. Your task is to partially encode a string message given to your program as an input and output the encoded message. Leave all letters except for the following:

  • F and f: replace with !
  • G and g: replace with @
  • T and t: replace with #
  • H and h: replace with $
  • Y and y: replace with %
  • B and b: replace with ^

For Example:
>After seeinG my dark Future, I can't continue living in the Boring past.
A!#er seein@ m% dark !u#ure, I can'# con#inue livin@ in #$e ^orin@ pas#.

At our resistance base, we have delivery drones. These are very simple flying robots that know only how to deliver boxes to the destination point. After some time, the drones begin to break. They'll move forward and then backward. We still keep a drone in circulation as long as it moves forward more often than backward. The drones log all their actions the console until it reaches the destination.
Your program should print the distance from the starting point to the destination. If, at some point, the drone performs more steps backward than forward, the program should terminate the delivery and output "Go back to base. Delivery failed." to the console.
You can assume that the drone flies along a straight line with no turns. If the drone outputs "forward", it means that it has moved 10 meters forward. Otherwise, if it moved backward, the output will be "backward". When the drone reaches the destination point, it prints "Destination reached." to the console In this case, the program should output the distance from the starting point to the destination. Use a switch to check the input from the drone.
Example 1:
>forward
>forward
>backward
>forward
>forward
>Destination reached.
30
Example 2:
>forward
>backward
>backward
Go back to base. Delivery failed.

Robot

The old walking drone tracking system just broke yesterday, and you need to write a new one.
The drone tracking system should output the coordinates of the drone once it's reached its destination. The drone starts its movement at the bottom left corner of the field with coordinates [0, 0], and can move up, or right, or both (diagonal; see picture). Your program should constantly read where the drone has moved until it writes "Destination reached." Then your program should output the coordinates of the drone in the format "[droneX, droneY]", where droneX is the x coordinate of the drone and droneY is its y coordinate.
Messages reporting drone movement that your program needs to read from the console have the following format:

  • up - movement up; y increases by one.
  • right - movement right; x increases by one.
  • diag - diagonal movement; x and y both increase by one.

For example:
>up
>right
>diag
>up
>diag
>Destination reached.
[3, 4]

Drone movement in c sharp course

At that point, I was really exhausted. Sara looked happy because I had managed to solve all of her tasks for the switch statement, and I was happy because I could finally get some sleep.

Go go go!

C# Beginner > 6 The truth > Switch statement

This site uses cookies. By continuing to browse this site you are agreeing to our use of cookies.

Got it!