Decision logic -`if`, `else`, and `else if` statements - and Boolean Expressions. Introduction to Programming. C# — Lesson Six(6)
Ferdinand Charles
Full Stack Software Engineer | AI/ML Engineer | Prompt Engineering Specialist| Large Language Model Whisperer | Digital Transformation Consultant | Cloud Solutions Architect | DevOps Practitioner | TensorFlow | AWS
UNIT 1
Decision logic (`if`, `else`, and `else if` statements) and Boolean Expressions
Introduction
The C# programming language allows you to build applications that employ decision-making logic. Branching logic enables your application to perform different instructions based on a set of conditions.
Suppose you want to display different information to the end user depending on some business rules. For example, what if you want to display a special message on a customer’s bill based on their geographic region? What if you want to give a customer a discount based on the size of their order? Or what if you want to display an employee’s title based on their level in the company? In each case, you would need to add decision logic.
By the end of this lesson, you’ll be able to write code that can change the flow of your code’s execution based on some criteria.
This lesson is one of the most exciting lessons because it opens a new world of branching code, allowing your applications to do more interesting things.
Learning objectives
In this module, you will:
Write code that evaluates conditions by using the statements if, else, and else if.
Build Boolean expressions to evaluate a condition.
Combine Boolean expressions by using logical operators.
Nest code blocks within other code blocks.
Prerequisites
Experience declaring, initializing, setting, and retrieving variables by using the int data type.
Experience printing messages to output by using Console.WriteLine().
Experience with string interpolation to combine variables into literal strings.
Experience working with the System.Random class to generate random numbers.
UNIT 2
The if statement
The most widely used branching statement is the if statement. The if statement relies on a Boolean expression that is enclosed in a set of parentheses. If the expression is true, the code after the if statement is executed. If the expression is false, the code after the if statement is skipped.
Exercise — Create a random-number game by using if statements
Let’s invent a game to help us write if statements. We’ll make up several rules to the game, and then we’ll implement them in code.
We’ll use the Random.Next() method to simulate rolling three six-sided dice. We’ll evaluate the values to calculate the score. If the score is greater than an arbitrary total, we’ll display a winning message to the user. Otherwise, we’ll display a losing message to the user.
If any two dice you roll result in the same value, you get two bonus points for rolling doubles.
If all three dice you roll result in the same value, you get six bonus points for rolling triples.
If the sum of the three dice rolls, plus any point bonuses, is 15 or greater, you win the game. Otherwise, you lose.
We’ll add to the number of rules as we expand our understanding of the if statement.
Important
We’ll make extensive use of the System.Random class which we covered in Lesson Five. If you need a refresher about how Random.Next() works, please refer to that lesson.
Step 1 — Write code that generates three random numbers and displays them in output
Run the following code snippet to run the code in?.NET Editor:
Random dice = new Random();
int roll1 = dice.Next(1, 7);
int roll2 = dice.Next(1, 7);
int roll3 = dice.Next(1, 7);
int total = roll1 + roll2 + roll3;
Console.WriteLine($"Dice roll: {roll1} + {roll2} + {roll3} = {total}");
We create a new instance of the System.Random class and store the reference to that object in the dice variable. Then, we call the Random.Next() method on the dice object three times, providing both the lower and upper bounds to restrict the possible values between 1 and 6. We save the three random numbers in the variables roll1, roll2, and roll3, respectively.
Next, we sum up the three dice rolls and save the value in the total variable.
Finally, we display all the values by using string interpolation.
When you run the code, you should see the following message (of course, the numbers will be different because they are randomly generated numbers):
Dice roll: 4 + 5 + 2 = 11
Step 1 was a setup step. Now, we can add the decision logic to our code to make the game more interesting.
Step 2 — Add an if statement to display different messages based on the value of the total variable
Modify the code from the previous step to include the if statement:
Random dice = new Random();
int roll1 = dice.Next(1, 7);
int roll2 = dice.Next(1, 7);
int roll3 = dice.Next(1, 7);
int total = roll1 + roll2 + roll3;
Console.WriteLine($"Dice roll: {roll1} + {roll2} + {roll3} = {total}");
if (total > 14) {
Console.WriteLine("You win!");
}
if (total < 15) {
Console.WriteLine("Sorry, you lose.");
}
We added two if statements to handle the winning and losing scenarios. Let’s focus on the first if statement.
The if statement is made up of three parts:
1. The if keyword.
2. A Boolean expression between parentheses ().
3. A code block defined by curly braces { }.
At runtime, the Boolean expression total > 14 is evaluated. If this expression is true and the value of total is greater than 14, the flow of execution will continue into the code defined in the code block. In other words, it will execute the code in the curly braces.
However, if the Boolean expression is false, the flow of execution will skip the code block. In other words, it will not execute the code in the curly braces.
Finally, the second if statement controls the message if the user loses. In the next unit, we’ll use a variation on the if statement to shorten these two statements into a single statement and more clearly express our intent.
What is a Boolean expression?
A Boolean expression is any code that returns a Boolean value, either True or False. The simplest Boolean expressions are the values true and false. Alternatively, a Boolean expression can be the result of a method that returns the value true or false. For example, here’s a simple code example that uses the string.Contains() method to evaluate whether one string contains another string:
string message = "The quick brown fox jumps over the lazy dog.";
bool result = message.Contains("dog");
Console.WriteLine(result);
if (message.Contains("fox")) {
Console.WriteLine("What does the fox say?");
}
Because the message.Contains(“fox”) returns a true or false value, it qualifies as a Boolean expression and can be used in an if statement.
Other simple Boolean expressions can be created by using operators to compare two values. Operators include:
==, the “equals” operator, to test for equality.
>, the “greater than” operator, to test that the value on the left is greater than the value on the right.
<, the less than operator.
>=, the “greater than or equal to” operator.
<=, the “less than or equal to” operator.
and so on
Note: — There is more to Boolean expressions than what we are discussing here, which is why, we will consider devoting an entire lesson to Boolean expressions in the future. We can choose from many operators to construct a Boolean expression, and we’ll cover only a few of the basics here.
In our example, we evaluated the Boolean expression total > 14. However, we could have chosen the Boolean expression total >= 15 because in this case, they’re the same. Given that the rules to our game specify “If the two dice, plus any bonuses, is 15 or greater, you win the game”, we should probably prefer the latter. We’ll make that change in the next step of the exercise.
What is a code block?
A code block is a collection of one or more lines of code that are defined by an opening and closing curly brace symbol { }. It represents a complete unit of code that has a single purpose in our software system. In this case, at runtime, all lines of code in the code block are executed if the Boolean expression is true. Conversely, if the Boolean expression is false, all lines of code in the code block are ignored.
There are code blocks at many levels in C#. In fact,?.NET Editor hides the fact that our code is being executed inside of a code block that defines a method. You’ll see this structure more acutely as you begin to write C# code by using Visual Studio Code or the Visual Studio IDE.
Code blocks can contain other code blocks. We’ll see that demonstrated later in this module as we nest one if statement inside of another.
Step 3 — Add another if statement to implement the doubles bonus
Next, let’s implement a new rule: “If any two dice you roll result in the same value, you get two bonus points for rolling doubles”. Modify the code from the previous step to match the following code listing:
Random dice = new Random();
int roll1 = dice.Next(1, 7);
int roll2 = dice.Next(1, 7);
int roll3 = dice.Next(1, 7);
int total = roll1 + roll2 + roll3;
Console.WriteLine($"Dice roll: {roll1} + {roll2} + {roll3} = {total}");
if ((roll1 == roll2) || (roll2 == roll3) || (roll1 == roll3))
{
Console.WriteLine("You rolled doubles! +2 bonus to total!");
total += 2;
}
if (total >= 15)
{
Console.WriteLine("You win!");
}
if (total < 15)
{
Console.WriteLine("Sorry, you lose.");
}
Here, we combine three Boolean expressions to create one large Boolean expression in a single line of code. This type of code is sometimes called a compound condition. We have one outer set of parentheses that combines three inner sets of parentheses separated by two pipe characters.
Two pipe characters || is the logical OR operator, which basically says “either the expression to my left OR the expression to my right must be true in order for the entire Boolean expression to be true”. If both Boolean expressions are false, the entire Boolean expression is false. We use two logical OR operators so that we can extend the evaluation to a third Boolean expression.
First, we evaluate (roll1 == roll2). If that’s true, the entire expression is true. If it’s false, we evaluate (roll2 == roll3). If that’s true, the entire expression is true. If it’s false, we evaluate (roll1 == roll3). If that’s true, the entire expression is true. If all three are false, the entire expression is false.
If the compound Boolean expression is true, we execute the following code block. This time, there are two lines of code. The first line of code prints a message to the user. The second line of code increments the value of total by 2.
Finally, we also changed the check to see if the user won to use the >= operator. That scenario more closely resembles the requirement we created as we began, but it should function identically to what we wrote previously.
if (total >= 15)
Step 4 — Add another if statement to implement the triples bonus
Next, let’s add another new rule: “If all three dice you roll result in the same value, you get six bonus points for rolling triples.” Modify the code from the previous steps to match the following code listing:
Random dice = new Random();
int roll1 = dice.Next(1, 7);
int roll2 = dice.Next(1, 7);
int roll3 = dice.Next(1, 7);
int total = roll1 + roll2 + roll3;
Console.WriteLine($"Dice roll: {roll1} + {roll2} + {roll3} = {total}");
if ((roll1 == roll2) || (roll2 == roll3) || (roll1 == roll3))
{
Console.WriteLine("You rolled doubles! +2 bonus to total!");
total += 2;
}
if ((roll1 == roll2) && (roll2 == roll3))
{
Console.WriteLine("You rolled triples! +6 bonus to total!");
total += 6;
}
if (total >= 15)
{
Console.WriteLine("You win!");
}
if (total < 15)
{
Console.WriteLine("Sorry, you lose.");
}
Here, we combine two Boolean expressions to create one compound Boolean expression in a single line of code. We have one outer set of parentheses that combines two inner sets of parentheses separated by two ampersand characters.
Two ampersand characters && is the logical AND operator, which basically says “only if both expressions are true, then the entire expression is true”. In this case, if roll1 is equal to roll2, and roll2 is equal to roll3, so roll1 must be equal to roll3 and the user rolled triples.
If you run the code, you might see output like this example:
Dice roll: 3 + 6 + 1 = 10 Sorry, you lose.
Or like this example:
Dice roll: 1 + 4 + 4 = 9 You rolled doubles! +2 bonus to total! Sorry, you lose.
Or like this example:
Dice roll: 5 + 6 + 4 = 15 You win!
Or, if you’re lucky, you’ll see this output:
Dice roll: 6 + 6 + 6 = 18 You rolled doubles! +2 bonus to total! You rolled triples! +6 bonus to total! You win!
But wait, should we really reward the player for getting both a triple bonus and a double bonus? After all, a triple implies that they also rolled a double. Ideally, this bonus doesn’t stack. They should be two separate bonuses. We have our first bug in logic.
领英推荐
Problems in our logic and opportunities to improve the code
Although we’ve made a good start and we’ve learned a lot about the if statement, Boolean expressions, code blocks, logical OR and AND operators, and so on, there’s much that can be improved. We’ll do that in the next unit.
Recap
· Use an if statement to branch your code logic. The if decision statement will execute code in its code block if its Boolean expression equates to true. Otherwise, the runtime will skip over the code block and continue to the next line of code after the code block.
· A Boolean expression is any expression that returns a Boolean value. Boolean operators will compare the two values on its left and right for equality, comparison, and more.
· A code block is defined by curly braces { }. It collects lines of code that should be treated as a single unit.
· The logical AND operator && aggregates two expressions so that both subexpressions must be true in order for the entire expression to be true.
· The logical OR operator || aggregates two expressions so that if either subexpression is true, the entire expression is true.
UNIT 3
Exercise — Use the `else` and `else if` statements
Previously, we used multiple if statements to implement the rules of our game. However, when we left off in the previous unit, there was opportunity for improvement. We can make an improvement to the expressiveness of the code and an improvement to fix a subtle bug in our code.
Improve code and fix a bug by adding else and else if statements
Next, we’ll use variants of the if statement to improve our code and fix a logic bug.
Step 1 — Use if and else statements instead of two separate if statements Instead of performing two checks to display the “You win!” or “Sorry, you lose” message, we’ll use the else keyword. Modify your code to match the following code listing:
Random dice = new Random();
int roll1 = dice.Next(1, 7);
int roll2 = dice.Next(1, 7);
int roll3 = dice.Next(1, 7);
int total = roll1 + roll2 + roll3;
Console.WriteLine($"Dice roll: {roll1} + {roll2} + {roll3} = {total}");
if ((roll1 == roll2) || (roll2 == roll3) || (roll1 == roll3))
{
Console.WriteLine("You rolled doubles! +2 bonus to total!");
total += 2;
}
if ((roll1 == roll2) && (roll2 == roll3))
{
Console.WriteLine("You rolled triples! +6 bonus to total!");
total += 6;
}
if (total >= 15)
{
Console.WriteLine("You win!");
}
else {
Console.WriteLine("Sorry, you lose.");
}
Here, if total >= 15 is false, the code block after the else keyword will execute. Because these two options are related opposites, this scenario is a perfect example of when to use the else keyword.
Using Nesting to remove the stacking bonus for doubles and triples
In the previous unit, we saw how we introduced a subtle logic bug into our application. Let’s fix bug that by using nesting.
Nesting allows us to place code blocks inside of code blocks. In this case, we’ll nest if and else statements (the check for triples) inside of another if statement (the check for doubles) to prevent them both from happening.
We’ll nest the check for triples inside of the check for doubles. Modify the code to match the following code listing:
int roll1 = 6;
int roll2 = 6;
int roll3 = 6;
int total = roll1 + roll2 + roll3;
Console.WriteLine($"Dice roll: {roll1} + {roll2} + {roll3} = {total}");
if ((roll1 == roll2) || (roll2 == roll3) || (roll1 == roll3))
{
if ((roll1 == roll2) && (roll2 == roll3))
{
Console.WriteLine("You rolled triples! +6 bonus to total!");
total += 6;
}
else
{
Console.WriteLine("You rolled doubles! +2 bonus to total!");
total += 2;
}
}
if (total >= 15)
{
Console.WriteLine("You win!");
}
else {
Console.WriteLine("Sorry, you lose.");
}
To test the code without running the application dozens of times, you can temporarily hard-code the values of the three roll variables by adding the following code before the line where total is declared and initialized.
To test that doubles works:
roll1 = 6; roll2 = 6; roll3 = 5;
When you run the code, you should see:
Dice roll: 6 + 6 + 5 = 17 You rolled doubles! +2 bonus to total! You win!
To test that triples work, modify the value of roll3:
roll1 = 6; roll2 = 6; roll3 = 6;
When you run the code, you should see this output:
Dice roll: 6 + 6 + 6 = 18 You rolled triples! +6 bonus to total! You win!
Step 3 — Use if, else, and else if statements to give a prize instead of a win-lose message
To make the game more fun, let’s change the game from win-or-lose to award fictitious prizes for each score. We’ll offer four prizes.
The player should win only one prize: If the player scores greater or equal to 16, they’ll win a House.
If the player scores greater or equal to 10, they’ll win a new car.
If the player scores exactly 7, they’ll win a new laptop.
Otherwise, the player wins a kitten.
Modify the code from the previous steps to the following code listing:
Run Random dice = new Random();
int roll1 = dice.Next(1, 7);
int roll2 = dice.Next(1, 7);
int roll3 = dice.Next(1, 7);
int total = roll1 + roll2 + roll3;
Console.WriteLine($"Dice roll: {roll1} + {roll2} + {roll3} = {total}");
if ((roll1 == roll2) || (roll2 == roll3) || (roll1 == roll3))
{
if ((roll1 == roll2) && (roll2 == roll3))
{
Console.WriteLine("You rolled triples! +6 bonus to total!");
total += 6;
}
else {
Console.WriteLine("You rolled doubles! +2 bonus to total!"); total += 2;
}
}
if (total >= 16)
{
Console.WriteLine("You win a new car!");
}
else if (total >= 10)
{
Console.WriteLine("You win a new laptop!");
}
else if (total == 7)
{
Console.WriteLine("You win a trip for two!");
}
else {
Console.WriteLine("You win a kitten!");
}
Note
Use the technique of temporarily hard-coding the roll variables to test each message. You can use if, else, and else if statements to create multiple exclusive conditions as Boolean expressions. In other words, when you want only one outcome to happen, but you have several possible conditions and results, use as many else if statements as you want. If none of the if and else if statements apply, the final else code block will be executed. The else is optional, but it must come last.
Recap
The combination of if and else statements allows you to test for a condition and perform code when a Boolean expression is true and run different code when the Boolean expression is false.
You can nest if statements to narrow down a possible condition. However, you should consider using the if, else, and else if statements instead.
Use else if to create multiple exclusive conditions.
An else is optional, but it must always come last.
UNIT 4
Challenge
Code challenges throughout these lessons reinforce what you’ve learned and help you gain some confidence before proceeding
Challenge: Improve renewal rate DSTV/GOTV of subscriptions
You’ve been asked to add a feature to DSTV company’s software. The feature is intended to improve the renewal rate of subscriptions to the DSTV software. Your task is to display a renewal message when a user signs in to the DSTV/GOTV software system and is notified that their subscription will soon end. You’ll need to add a couple of decision statements to properly add branching logic to the application to satisfy the requirements.
Step 1 — Delete all code from the earlier exercises in?.NET Editor Select all the code in?.NET Editor, and then press Delete, or press Backspace to delete it.
Step 2 — Copy the following code to?.NET Editor as a starting point
Random random = new Random();
int daysUntilExpiration = random.Next(12);
int discountPercentage = 0;
// Your code goes here
Important
You can remove only the code comments. In other words, you may remove the line of code that starts with //, but you may not remove any other code. Furthermore, you must use all the variables in your code.
Step 3 — Use two if statements to implement the following business rules (branch or nest three in the first if statement)
Rule 1. If the user’s DSTV/GOTV subscription will expire in 10 days or less, display the message:
Your subscription will expire soon. Renew now!
Rule 2. If the user’s DSTV/GOTV subscription will expire in 5 days or less, display the messages:
Your subscription expires in x days. Renew now and save 10%!
NOTE: — Make sure to substitute x for the value stored in the variable daysUntilExpiration.
Rule 3. If the user’s subscription will expire in 1 day, display the message:
Your subscription expires within a day! Renew now and save 20%!
Rule 4. If the user’s subscription has expired, display the message:
Your subscription has expired.
Rule 5. If the user’s subscription will expire in more than 10 days, display nothing.
UNIT 5
Solution
The following code is one possible solution for the challenge from the previous unit.
Random random = new Random();
int daysUntilExpiration = random.Next(12);
int discountPercentage = 0;
if (daysUntilExpiration == 0)
{
Console.WriteLine("Your subscription has expired.");
}
else if (daysUntilExpiration == 1)
{
Console.WriteLine("Your subscription expires within a day!");
discountPercentage = 20;
}
else if (daysUntilExpiration <= 5)
{
Console.WriteLine($"Your subscription expires in {daysUntilExpiration} days.");
discountPercentage = 10;
}
else if (daysUntilExpiration <= 10)
{
Console.WriteLine("Your subscription will expire soon. Renew now!");
}
if (discountPercentage > 0)
{
Console.WriteLine($"Renew now and save {discountPercentage}%.");
}
This code is merely “one possible solution” because a lot depends on how you decided to implement the logic. As long as you got the right results per the rules in the challenge, and you used two if statements, you did great!
If you’re successful, congratulations!
UNIT 6
Summary
Our goal in this lesson was to add branching logic to our code by using decision statements.
Using if, else, and else if statements, we evaluated one or more Boolean expressions to change the execution path of our application. Depending on some condition, we could execute some code and ignore other code. Without decision statements, our applications would lack the ability to automate common business, gaming, and scientific tasks required in modern applications.
We’ll come to rely on the techniques we learned in this lesson in virtually every application we build.
There are two other ways to introduce decision logic into our application. We’ll introduce the switch statement and the conditional operator in other lessons.
Important
If you had trouble completing this challenge, maybe you should review the previous units before you continue on. All new ideas we discuss in other lessons will depend on your understanding of the ideas that were presented in this lesson.
Thank you for your time.!!! Hope to see you in my next article.
Bye for now.