4. Decisions

Chapter 0100 2

Help Make These Materials Better!

I am actively working to complete and revise this eBook and the accompanying videos. Please consider using the following link to provide feedback and notify me of typos, mistakes, and suggestions for either the eBook or videos:

{feedback-url}

This is the working draft of a very incomplete eBook. Content will change as chapters are developed and refined. Most noticeably (other than stuff that’s just missing) is the presence of placeholder links where I haven’t quite finished videos. Check back later for a more complete version.

What’s the Point?

  • Create Boolean expressions using comparison and logical operators

  • Use if and if-else statements to make decisions in your code

  • Create if-else if structures to choose between multiple options

  • Understand the use of switch statements to choose between multiple options

Source code examples from this chapter and associated videos are available on GitHub.


Decisions, or branching gives our programs the ability to execute different code depending on what’s happening as it runs. At the core of decisions is the concept of Boolean logic, which is named after a 19th-century mathematician named George Boole. Boolean logic is the foundation of the if statements that will allow our programs to branch.

4.1. Boolean Expressions

Until now, our programs have all executed very sequentially and predictably—​one line of code after another. How boring! To give our programs the ability to branch and execute different code based on different conditions, we need to introduce the concept of decisions.

In computer programming, a decision is made based on a Boolean expression, which is an expression that evaluates to either true or false. Think of Boolean expressions as questions that can be answered with a simple "yes" or "no". Is this student’s GPA high enough to qualify for the scholarship? Has this cell phone customer used all of their data? Did the user type "exit"?

The true or false value of a Boolean expression can be used to determine which code block will execute next, so it’s important to understand how they work.

Time To Watch!

Boolean Logic in C#

4.1.1. Boolean Values

The simplest way to use Boolean in C# is with the keywords true and false. These can be assigned to variables of type bool:

Example 4.1 - Declaring and assigning Boolean variables in C#.
1
2
bool isTimAmazing = true;
bool isClassBoring = false;

4.1.2. Comparison Operations

Also known as relational operations, comparison operations are expressions that compare two values. You will remember them from math class. Is x greater than y? Is a less than or equal to 10? Is c equal to d? Relational operators, like arithmetic operators, are binary operators that require two operands. In other words, we need two values to compare. In our math class, we could draw symbols that aren’t on our keyboard, like a ≥ for "greater than or equal to." In C#, where we have to stick with stuff on our keyboard, we use the following symbols:

Table 1. C# comparison operators
Operator Description

==

Equality (checks if two values are equal)

!=

Inequality (checks if two values are not equal)

<

Less-than

>

Greater-than

<=

Less-than-or-equal-to

>=

Greater-than-or-equal-to

A comparison operation will always evaluate to either true or false. We can store that result in a bool variable, as shown below, and we’ll also learn how to use these expressions in if statements later in this chapter.

Example 4.2 - Using comparison operators in C#
1
2
3
4
bool canBuyAlcohol = age >= 21;
bool isNegative = number < 0;
bool isArethaFranklin = name == "Aretha Franklin"; (1)
bool isArethaFranklin2 = name.equals("Aretha Franklin"); (2)
1 This statement uses the -- operator to check if two strings are equal.
2 This statement uses the equals() method to check if two strings are equal.

These assignment statements work like any other: the expression to the right of the equals symbol is evaluated, and the result is stored in the variable on the left.

In C#, we can test string equality with the == operator or the equals() method. This is different from Java, where we can’t use the == operator on String values. I mention it here because it’s a common source of confusion for students who are learning both languages at the same time.

4.2. if Statements

The if statement is the basic decision-making structure in C#. It allows us to execute a block of code only if a specified condition is true.

The syntax of an if statement is the keyword if, followed by a Boolean expression in parentheses, followed by a block of code in curly braces. If the Boolean expression evaluates to true, the block of code will execute. If the Boolean expression evaluates to false, the block of code will be skipped. In either case the program will continue executing the next line of code after the if-block.

Example 4.3 - A basic if statement in C#.
1
2
3
4
5
6
int age = 20;
if (age < 21)
{
    Console.WriteLine("You can't buy alcohol.");
}
Console.WriteLine("Keep that in mind when you go to the store!");

In this example, the if statement checks if the variable age is less than 21. Since 20 is less than 21, the Boolean expression evaluates to true, and the block of code inside the if statement (lines 3 through 5) is executed—​and it prints "You can’t buy alcohol." The program then continues to the next line of code, which prints "Keep that in mind when you go to the store!"

If the value of age were 22, the Boolean expression would evaluate to false, and the block of code inside the if statement would be skipped. The program would then continue to the next line of code, which prints "Keep that in mind when you go to the store!" Line 5 will execute every time the program runs, regardless of the value of age.

Keep in mind, the parentheses after the if keyword can contain any Boolean expression—​not just this simple example.

4.3. Adding an else Block

An if statement simply determines whether or not to execute a single block of code. If we want to choose between two blocks of code, we can add an else block to the if statement. The syntax is straightforward: after the if block, add the keyword else, followed by a block of code in curly braces.

Example 4.4 - An if-else statement in C#.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
int age = 20;
if (age < 21)
{
    Console.WriteLine("You can't buy alcohol.");
}
else
{
    Console.WriteLine("You can buy alcohol.");
}
Console.WriteLine("Keep that in mind when you go to the store!");

An if-else statement will always execute one block of code or the other, but never both. Basically, it’s an either-or situation.

Time To Watch!

if and if-else Statements in C#

File from video:

Interesting!

C# includes a shorthand form of an if-else statement called the ternary operator, which uses the question mark symbol. It’s a useful little trick, but it can be confusing for beginners—​and for the people reading our code later. We won’t look at them in this course, but a web search should turn up plenty of examples if you are curious.

Assignments in my course require you to use complete if-else statements, so you shouldn’t use the ternary operator in code you submit to me.

4.4. The if-else if Structure

The basic if-else structure is great for choosing between two blocks of code, but what if we have more than two options? To handle this, we can chain multiple if-else statements together.

This if-else if structure isn’t really a thing in C#. This is really just a way to write a series of if statements that are all part of the same decision-making process. But it’s a useful made-up name to help beginners understand the concept, so we’ll use it here.
Example 4.5 - Use of an if-else if structure to select one option from many.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
string input = "";
int trackNum = -1;
string songTitle = "";

Console.Write("Enter track number: ");
input = Console.ReadLine();
trackNum = Convert.ToInt32(input);

if (trackNum == 1)
{
    songTitle = "Peter Piper";
}
else if (trackNum == 2)
{
    songTitle = "It's Tricky";
}
else if (trackNum == 3)
{
    songTitle = "My Adidas";
}
else if (trackNum == 4)
{
    songTitle = "Walk This Way";
}
else if (trackNum == 5)
{
    songTitle = "Is It Live";
}
else if (trackNum == 6)
{
    songTitle = "Perfection";
}
else
{
    songTitle = "Not found";
}

Console.WriteLine($"Track #{trackNum} on side one of Raising Hell by Run D.M.C. is {songTitle}.");

In this example, the user inputs a track number and we use an if-else if structure to output the song’s title.

The code begins with the first statement, and if it evaluates to true, the corresponding block of code will execute—​setting the song title to "Peter Piper". If the first statement evaluates to false, the program will move on to the next else if statement and check that condition, and so on through all of the else if blocks. Once an expression evaluates to true and the corresponding code block is executed, the program will then jump to the first line of code after the end of the if-else if structure—​the WriteLine() statement. Only one block of code can execute. If the program gets through the entire structure without finding a true condition, it will execute the block of code in the else block, if one is present.

As is often the case in programming, there are multiple ways to solve this problem. As we learn more (or if you have previous coding experience), you may find that you prefer a different way to write this code. That’s great, and is part of the fun of coding. But keep in mind that your instructor’s job is to assess your understanding of the concepts being taught. You can’t get points on an if-else-if assignment if you don’t use an if-else-if structure!

In summary, an if-else if structure can execute, at most, one block of code. If an else block is included at the end, it guarantees that exactly one block of code will execute.

Time To Watch!

if-else if Statements in C# [COMING SOON!]

Take It for a Spin

This is a good time to stop and try out what you’ve learned so far. The Coding Practice assignment for this chapter can be completed with the concepts covered to this point.

4.5. Nested if-else Statements

If we want a block of code to execute only if two different conditions are met, we can place if statements inside of each other, which is called nesting. Nested if statements check multiple conditions in a hierarchical way: if one condition is met, it will proceed and check the next condition; if the first condition is not met, it will skip the inner if block.

Just like the if-else if structure, this is not a special structure in C#--again, it’s just a useful way to help beginners understand how and when this way of organizing if-else statements is useful. Indeed, what I call an if-else if structure is really just nested if statements, too.
Example 4.6 - Basic structure of a nested if-else statement.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
if (condition1)
{
    if (condition2)
    {
        // executes if both condition1 and condition2 are true
    }
    else
    {
        // executes if condition1 is true and condition2 is false
    }
}
else
{
    // executes if condition1 is false
}

In the example below, the outermost if-else structure checks the high temperature of the day. The if-else structures within those blocks check the average wind speed and return an appropriate description.

Example 4.7 - Use of nested if-else statements to select one option from many.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
string input = "";
int sideNum = -1;
int trackNum = -1;
string songTitle = "";

Console.Write("Enter side number: ");
input = Console.ReadLine();
sideNum = Convert.ToInt32(input);

Console.Write("Enter track number: ");
input = Console.ReadLine();
trackNum = Convert.ToInt32(input);

if (sideNum == 1)
{
    if (trackNum == 1)
    {
        songTitle = "Peter Piper";
    }
    else if (trackNum == 2)
    {
        songTitle = "It's Tricky";
    }
    else if (trackNum == 3)
    {
        songTitle = "My Adidas";
    }
    else if (trackNum == 4)
    {
        songTitle = "Walk This Way";
    }
    else if (trackNum == 5)
    {
        songTitle = "Is It Live";
    }
    else if (trackNum == 6)
    {
        songTitle = "Perfection";
    }
}
else if (sideNum == 2)
{
    if (trackNum == 1)
    {
        songTitle = "Hit It Run";
    }
    else if (trackNum == 2)
    {
        songTitle = "Raising Hell";
    }
    else if (trackNum == 3)
    {
        songTitle = "You Be Illin'";
    }
    else if (trackNum == 4)
    {
        songTitle = "Dumb Girl";
    }
    else if (trackNum == 5)
    {
        songTitle = "Son of Byford";
    }
    else if (trackNum == 6)
    {
        songTitle = "Proud to Be Black";
    }
}
else
{
    songTitle = "Not found";
}

Console.WriteLine($"Track #{trackNum} on side {sideNum} of Raising Hell by Run D.M.C. is {songTitle}.");

Time To Watch!

Nested if-else Statements in C# [COMING SOON!]

4.6. Using Logical Operators

In addition to the relational operators, C# also includes logical operators we can use to make more complex Boolean expressions. A logical operator is a binary operation, so it takes two operands—​but the operands are Boolean expressions instead of numbers.

Table 2. C# logical operators
Operator Name Description

&&

AND

Evaluates to true if both operands are true

||

OR

Evaluates to true if either operand is true

!

NOT

Evaluates to true if the operand is false; evaluates to false if the operand is true

These operators can be used to combine multiple Boolean expressions into a single, more complex expression. For example, we could check if a student is eligible for a scholarship based on both their GPA (3.5 or better) and their age (younger than 25).

Example 4.8 - A decision using a logical AND operation in C#.
1
2
3
4
if (gpa >= 3.5 && age < 25)
{
    Console.WriteLine("You qualify for the scholarship!");
}

In this example, the && operator is used to combine two Boolean expressions. The if statement will only execute the block of code if both expressions are true.

Often, the logic we create using an AND operation can be implemented using nested if-else statements, and vice versa.

The OR operation is similar, but only one of the expressions needs to be true for the entire expression to be true.

Example 4.9 - A decision using a logical OR operation in C#.
1
2
3
4
5
6
7
bool isTimAmazing = false;
bool isClassFun = true;

if (isTimAmazing || isClassFun)
{
    System.out.println("You should take this class!");
}

Both operands in an AND or OR operation have to be complete Boolean expressions. Put another way, each side of the && or || operator must be able to evaluate to true or false on its own. The following code is a very common beginner mistake and will not compile:

if (percentage >= 80 && < 90) { …​ }

This reads like "if the percentage is greater than or equal to 80 and less than 90," but the second part of the expression is not a complete Boolean expression. We need to include the variable name and the comparison operator on both sides of the && operator.

4.6.1. The NOT Operator

The NOT operation is a little different, as it only takes one operand (making it a unary operator_, if you’re nerdy about words, like I am). It simply inverts the value of the operand. If the operand is true, the NOT operation will evaluate to false. If the operand is false, the NOT operation will evaluate to true.

Example 4.10 - A decision using a logical NOT operation in C#.
1
2
3
4
5
6
bool isTimAmazing = false;

if (!isTimAmazing)
{
    System.out.println("At least his mom still loves him!");
}

4.6.2. Range Checking

There are a lot of situations where we might need to combine multiple conditions to make a decision, but one of the most common is range checking. Range checking means we want to see if a value is within a specified range.

A common example of range checking is to convert a percentage grade to a letter grade.

Example 4.11 - Range checking using logical operators in C#.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public String GetLetterGrade(int percentage)
{
    if (percentage >= 90 && percentage <= 100)
    {
        return "A";
    }
    else if (percentage >= 80 && percentage < 90)
    {
        return "B";
    }
    else if (percentage >= 70 && percentage < 80)
    {
        return "C";
    }
    else if (percentage >= 60 && percentage < 70)
    {
        return "D";
    }
    else if (percentage >= 0 && percentage < 60)
    {
        return "F";
    }
    else
    {
        return "Invalid percentage";
    }
}

The AND operator && used in this example means that in order to return "B", for example, the percentage must be greater than or equal to 80 and the percentage must be less than 90. If either of those conditions is not met, the program will move on to the next else if statement.

4.7. switch Statements

C# includes a structure called a switch statement that can be used to choose between multiple options. It is essentially another way to write an if-else if structure, but it can be more readable and easier to write in some situations. I generally consider switch structures to be optional—​you can complete all of the assignments in this course without using them—​but they are a useful tool to have in your programming toolbox. And since you see them often in code written by others, it’s good to know how they work.

The basic structure of a switch statement is as follows:

Example 4.12 - A basic switch statement in C#.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
switch (expression)
{
    case value1:
        // Code to be executed if expression equals value1
        break;
    case value2:
        // Code to be executed if expression equals value2
        break;
    case value3:
        // Code to be executed if expression equals value3
        break;
    default:
        // Code to be executed if expression doesn't match any case
}

The expression in the parentheses after the switch keyword is evaluated, and then the program will jump to the case that matches the value of the expression. If there is no match, the program will execute the default block, if it is present.

The break statement is used to exit the switch block due to a behavior of switch that can be confusing to beginners, known as fall-through. If we don’t include a break statement at the end of a case block, the program will continue executing the code in the next case block, even if the value of the expression doesn’t match the case. This can be useful in some situations, but it’s generally not what you want, so you’ll usually see a break statement at the end of each case block.

Example 4.13 - A switch statement in C#.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
public void TrafficInstructions(string lightColor)
{
    switch (lightColor)
    {
        case "red":
            Console.WriteLine("Stop! In the Name of Love!");
            break;
        case "yellow":
            Console.WriteLine("Slow down!");
            break;
        case "green":
            Console.WriteLine("Go!");
            break;
        default:
            Console.WriteLine("Invalid light color.");
    }
}

Check Yourself Before You Wreck Yourself (on the assignments)

Chapter Review Questions

  1. What type of value must go inside the parentheses of an if statement?

  2. Write an if statement that checks if the variable volume is less than 11. If it is, print "This amp goes to eleven!".

  3. What does the == operator do, and how is it different from =?

  4. Explain the difference between using else if and just writing another if statement?

  5. Write a comment that explains the following code:

    1
    2
    3
    4
    if (scratchCount >= 3 && <= 6)
    {
        condition = "very good";
    }
    
  6. Rewrite the following if-else if structure using a switch statement:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    if (trackNumber == 1)
    {
        Console.WriteLine("Playing: Brown Sugar");
    }
    else if (trackNumber == 2)
    {
        Console.WriteLine("Playing: Sway");
    }
    else if (trackNumber == 3)
    {
        Console.WriteLine("Playing: Wild Horses");
    }
    else
    {
        Console.WriteLine("Playing: Unknown Track");
    }
    

Sample answers provided in the Liner Notes.