Selection Statements - C# Programming for Beginners (2015)

C# Programming for Beginners (2015)

Chapter 3: Selection Statements

Logic building lies at the core of every program. Logic building involves making decisions. In our daily lives, we make decisions based on certain criteria. For instance, if the weather is rainy, we decide not to play outside; if the weather is foggy, we drive carefully. There are hundreds of small decisions which we have to make every day. In the same way, a computer program has to make decisions during execution. Based on those decisions, a particular piece of code is executed, leaving some other piece of code unexecuted. For instance, you might want your program to take input from the user about the weather and then recommend if the user should play outside or not. In C#, this is done via selection statements (also known as control statements). In this chapter we are going to study C# selection statements.

Contents

· If/Else Statements

· Switch Statements

1- If/Else Statements

The “if” statement is used to execute a piece of code if the “test-expression” entered in the body of the statement evaluates to be true. Example1 demonstrates the usage of “if” statements.

Example1:

using System;

namespaceMyCSharpApplication

{

class Program

{

static void Main(string[] args)

{

string weather = "sunny";

if (weather == "rainy")

{

Console.WriteLine("Don’t play outside, it’s rainy.");

}

if (weather == "sunny")

{

Console.WriteLine("You can play outside, it’s sunny.");

}

Console.Read();

}

}

}

In Example 1, we have initialized a string type variable “weather” to “sunny”. We have then used two “if” statements. The first “if” statement evaluates if the variable “weather” contains the value “rainy”. This expression would return false because the variable “weather” contains the string “sunny”. The control would shift to the next “if” statement, where the comparison of the variable “weather” will be made with the string “rainy”. This expression will return true and the code block followed by this if statement will execute. The output of Example1 is shown as follows:

Output1:

You can play outside, it’s sunny.

There is a problem with using “if” statements. If the expression in the first “if” statement returns true, the comparison with the proceeding “if” statements will still be made. This is not desirable in some cases. For instance what if we want that if “weather” is equal to “rainy”, the next “if” statement which compares weather with “sunny”, should not execute? In such scenarios we use “else” and “if/else” statements. Example2 demonstrates this concept.

Example2:

using System;

namespaceMyCSharpApplication

{

class Program

{

static void Main(string[] args)

{

string weather = "rainy";

if (weather == "rainy")

{

Console.WriteLine("Don’t play outside, it’s rainy.");

}

else if (weather == "sunny")

{

Console.WriteLine("You can play outside, it’s sunny.");

}

else

{

Console.WriteLine("Weather cannot be determined, try again.");

}

Console.Read();

}

}

}

In Example2, the variable “weather” has been initialized to “rainy”. Therefore, the first “if” statement would be executed. After the “if” statement, we have used an “if/else” statement to evaluate if “weather” is equal to “sunny”. But since the first “if” statement is true, the condition in the “if/else” statement would not execute, unlike multiple “if” statements where the conditions in proceeding statements are also evaluated, even if the first “if” statement is true. You can use as many “if/else” blocks after the “if” statement. You can also use one “else” statement after the “if” statement if you have to make a selection between two code blocks based on one condition. The output of Example2 is as follows:

Output2:

Don’t play outside, it’s rainy.

2- Switch Statement

“If/else” statements are good to use if you have to make a small number of comparisons. However, in the case of a larger number of comparisons, switch statements are a better alternative. To see a “switch statement” at work, let’s jump straight to the third example of this chapter.

Example3:

using System;

namespaceMyCSharpApplication

{

class Program

{

static void Main(string[] args)

{

string weather = "cloudy";

switch (weather)

{

case "rainy":

Console.WriteLine("Don’t play outside, it’s rainy.");

break;

case "sunny":

Console.WriteLine("You can play outside. It’s sunny.");

break;

case "cloudy":

Debug.WriteLine("Play but take your umbrella with you, it’s cloudy.");

break;

default:

Console.WriteLine("Weather cannot be determined");

break;

}

Console.Read();

}

}

}

Switch statements start with a keyword “switch” followed by a pair of opening and closing round brackets. Inside these brackets, we enter the variable which we want to compare. In Example3, we initialized the variable “weather” and assigned it the string “cloudy”. Inside the switch statement there are multiple case statements. Each case has a string value mentioned with it followed by a colon. Underneath every case statement, a code segment has been added. The code segment of that case will be executed based on whose value matches with the string variable “weather” mentioned in the opening and closing round brackets of the switch statement. Since the “weather” variable contains the string “cloudy”, the code segment of third case statement would be executed. It is also noteworthy that after every case statement, the “break” keyword has been mentioned. This is to avoid further case comparisons, in case a “case” statement has already been matched. If none of the case matches with the variable of the switch statement, the code after the “default” statement is executed which is mentioned in the end. The output of the code in Example3 is as follows:

Output3:

Play but take your umbrella with you, it’s cloudy.

Exercise 3

Task:

Initialize an integer type variable to a random value. Write a switch statement containing four cases. One of the case values should match the integer variable you initialized. In each case statement code segment, display different gifts. Display PS4 as a gift against the integer value you initialized.

Solution

using System;

usingSystem.Diagnostics;

namespaceMyCSharpApplication

{

class Program

{

static void Main(string[] args)

{

int lottery = 451876;

switch (lottery)

{

case 467681:

Console.WriteLine("You won a mobile set.");

break;

case 451876:

Console.WriteLine("You won a PS4.");

break;

case 742167:

Debug.WriteLine("Sorry you won nothing.");

break;

case 741963:

Debug.WriteLine("You won a cinema ticket");

break;

default:

Console.WriteLine("Sorry you won nothing.");

break;

}

Console.Read();

}

}

}