cs046 ยป

Contents

Introduction

So far our programs always do the same thing. I mean when when we run it a second time, it does exactly what it did before. >> I don't get it. We just learned about reading input. When you run the program again with different inputs, it'll do something different. >> That's not exactly what I mean. Whenever I run the program again, it runs exact same lines of code. What if I only want to add a friend if the friend's not already there? >> I think the time has come to, to learn about programming decisions. Then your program can take different actions depending on circumstances. For example, you could skip the lines of code that do the adding if the friend's already in the list. That's exactly what I want, let's do that.

Introducing Molly

My name's Molly Mackinlay, I'm from Belleview Washington and I'm a senior here at Stanford. And I first got into computer science when I was doing a first robotics program at my high school. I didn't take any coding classes until I got to Sanford and I took CS106A, my freshman year, fall quarter. And I loved it, but before that I thought I was interested in math, science, maybe engineering. And so I took an engineering course in the summer at Cornell University, trying to figure out if that's something I was interested in. And there I got to tour their HCI lab, which is Human Computer Interaction, and that studies how people interact with technology. And I was really interested in how to design technology for people. And make it something that was going to be both effective and really useful for them and that's what really got me excited about exploring CS. Because computer science is all about designing and solving problems that are going to be useful for the people that are using these programs. And so from there I took a lot of really amazing CS classes here. And from there I was sold. And I took the rest of the CS classes and had a really great time with it.

The if Statement

Hello, and welcome to this new lessons. In this lesson you will learn how your programs can make decisions. Let's look at an example. Here you have a typical elevator panel, and yes elevators are controlled by computers these days. And if you look at the buttons, you will notice that there are buttons for 10, 11, because, many people are superstitious and don't want to be in the 13th floor of a building. Now, contrary to popular belief, the 13th floor is not filled with secret government offices. There actually is a 13th floor, they just call it the 14th. So, the software that controls the elevator car needs to adjust for this human foible. Here's how you can do that in Java. Let's say floor is the number as provided by the user, 10, 11, 12, 14, 15, 16 or whatever, and now we want to compute that actual floor. Then we need to make a decision. In Java you use the if statement to make decisions, and you enclose the condition in parenthesis. Then you use a pair of braces, and inside you put the statement or statements that you want to have executed when this condition is true. So, if the floor is greater than 13, then we want it to adjust by subtracting 1. On the other hand, if the condition is false, then we'll carry out the actions in the else part of this statement. In which case, the actual floor number equals the floor number without any adjustment. And that's all there is to it. Let's go over the important parts again. The keyword if starts out the conditional statement. The condition goes in here, and is surrounded by parentheses. If the condition is true, then the part following the if is executed. And if the condition is false, then the part after the else clause is executed. Alright, now it's your turn. In some Asian countries, it's not the number 13 that brings bad luck, but the number 14. And those elevators wouldn't have a number 14. And in fact, just to play it safe, some property owners eliminate both the 13 and translates the user selected number to the actual floor number. And know, there are no hidden floors with secret government offices.

The if Statement

So, your job was to adjust this program, so that it works for the building where the 13th and 14th floor should be skipped in the elevator. So that means the numbers from 1 to 12 should stay unchanged, there won't ever be an input of if it's greater than 14, then we want to subtract 2 and not 1. And those are the two changes that you need to make to the program and it'll work. There are a couple of other odds and ends about the if statement that I want to briefly talk about. So, you know now that the if statement makes a decision. You go one way or another, depending on some condition. Now, sometimes your code is arranged so that you don't actually have a decision to do one thing or another. But the decision has between one and nothing at all. For example, over here, I've rearranged the code for computing the actualFloor of it. I'm initializing actualFloor with the floor, and then I only need to adjust it if the floor is greater than 13 and otherwise, I need to do nothing at all. In this case, it is perfectly legal to omit the else part. That's like if you only choose between doing something or just staying in place. It's okay to do more than one thing, you could put other actions inside here, maybe a print statement. Generally, in more complicated situations, there's going to be several statements in between the braces. Conversely, if there is only one action here, it's legal to omit the braces. But we won't ever do that. It's just clearer to always put them there. Makes the code easier to read. Now, go ahead and work out a couple more practice problems with Sarah. And then, we'll talk more about how these conditions are formed.

Discounted Prices

An airline is having a sale, maybe it's time to go on vacation. They're using this Java code, to calculate a discounted price. If a flight to Las Vegas was originally $95, what's it's price after the discount? If the original price of a flight to Chicago was $100, what's it's price now? What's the discounted price? If the original price of a fight to New York City is $105. What its discounted price?

Discounted Prices

Lets trace the code to find the answer. If the price is 95, then the originalPrice is less than 100, so it'll skip the first part of the if and go into the else. The discountedPrice will be the originalPrice, 95 minus 10. If the original price is 100, 100 is still not greater than 100, so we still go into the else. And get original price minus 10. If the original price was 105 though, 105 is greater than 100. So we day, discounted price is the original price minus 20. And we get 85.

Is This Discount The Same

What if I change the if and the else? Switch them around and make the greater than into a less than. Will the discounted prices computed by this piece of code be the same as the prices computed by this piece of code? If we instead use this piece of code, what will the discounted price for a flight to Las Vegas be? How about for Chicago and New York?

Is This Discount The Same

The flight for Las Vegas won't change and the flight to New York City won't change, but the flight to Chicago will be less this time. When we write the condition this way, the original price 100 will not be less than 100, so it will go into the L's and subtract 20. Whereas before, it went into the L's and subtracted only 10. For the threshold value, it matters whether we say original price is greater than 100 or original price is less than 100. Even if we switch the if and else clauses because it changes which group 100 falls in.

Relational Operators

Here I'm back to tell you how to write conditions in Java. Those conditions that you can put inside an if statement to make a decision. Often times you want to compare two values to see which one is smaller, which one is larger and there are a bunch of operators that you can use. Here's a list of them. A couple of them look just like what they look in regular mathematics. The others look slightly different. This one here, you would write as greater than or equal, or maybe greater than or equal, like that, in math. This one here is a less than or equal. This one here is a simple equality, and this one here is a not equal. Of course, these three symbols were chosen because there's no keyboard character , for the mathematical symbols. The equal, equal on the other hand was chosen because the plain old equal already has another meaning. In Java you use the equal, equal for comparison and the single equal sign for assignment. If you want to assign a value to a variable, here we want to assign the number 13 to the variable 4. Then we use the equal sign, and of course afterwards, floor is 13. If on the other hand, we want to test whether or not floor equals 13, then we use the equal, equal comparison symbol. Let's put if statements and relational operators to use in a fun graphical way, to draw flags. Here you see the flag of Indonesia, as simple as flags get, red on top, white on the bottom. Here you see the outline of a simple class for drawing a flag. Its get color at method, its called for every x and y value in the flag, your job will be to complete it so that the correct colors appear. You'll want to know the dimensions of the flag, so that you can decide when to use red and when to use white. And they're available to you in these instance variables. Don't worry about how the get color at method is, called. You can actually peek below and see it, but it uses loops, which we only introduce in the next lesson. Right now your job , is to fill out this method here. Put in a condition here, select the right colors. And as an added challenge, I want you to use the greater or equal operator. Now be careful, for exactly half of the rows, you want red, and for exactly half of the rows, you want white.

Relational Operators

Here's how I figured it out. If I look at an arbitrary point, x and y, where as always in our graphical coordinate systems, x grows this way and y grows this way, downward. And it's clear that the x value here has nothing to do with which color to chose. But the y value does, so I have to worry about the y value being. Greater than or maybe greater equal, we'll come back to that in a minute, then half the height. Now if it's greater than or greater than equal, or less than or less than equal, it's easy if it would make these things wrong. So, let's look at the actual numbers. Let's assume that the height is 200. In that case the Y values can be from 0 to 199. So, if they're from 0 to 99 then I want red. And if they're from 100 to 199 then I want white. So, if height is wide. So, this is exactly the right condition, we'll put it in here and otherwise I want Red. Let me put it in and demo it to you. I'll just make a flag, many flags as I want in a half times as wide as they are tall and I'll use the same here. And here it is. Red on top, white on the bottom. Let's move on to a more complicated flag.

Draw A Flag With 3 Colors

Here is the French flag with three colors blue, white, and red. So, here it looks like we have to make three decisions. Are we in the first third, the middle third, or the last one? In java you would start out with the first condition, and I'll leave it to you to fill in the details in the exercise. Then, for the next part, you'll use an else if clause, so you simply write else if followed by another condition. And finally, you use an else for the remaining possibility. So, here you need to supply two conditions, is the point in the left, is it in the middle or otherwise, of course, it has to be in the rightmost part. This construction with if, else if. You can have other answers if you'd like. And then, finally is a else. This is what you do anytime you get multiple decisions. And I get worked down from the top to the bottom as you would expect. The first condition gets checked if it's fulfilled the statement is executed in here, and everything else is skipped. On the other hand, if the first condition wasn't true, one would move to check the second condition and if that one was true, it would be executed. If it wasn't, then the third one would be executed. In other words, exactly one of these three blocks is executed, depending on which condition is true or whether none of them is true. Well, now it's your turn to try that with the French flag. Again, you'll be given a point x y that could fall anywhere within the flag. And you need to make a decision whether to return blue, white, or red. And when you do that be sure to use an if, else if, else construction.

Draw A Flag With 3 Colors

Well, let's have a look at how to do this. Again, we're giving an arbitrary point on the flag. Let's remember that x moves this way, y moves this way. So, in this case the y value doesn't matter at all. What matters is where x is. The total width here is given to us, so this cutoff here is width over 3 and this one is width times 2 over 3. So, the first condition here is going to be x less than width over 3 or maybe less than equal width over 3. Let's settle that. So, let's assume that the width was 300, then x could be any value between 0 and value that stays in this branch here should be x equals 99. With the 300, width over 3 is 100. So the less than is correct. We want to be less than 100 to stay here. As soon as we're between 100 and less than 2 3rds of the width, we want to be in the middle brand, branch. And, finally, if neither of those is true, then we want to be here. And thats the code. The takeaway is, if you need to make multiple decisions, then you use the if, else if, else clause. Sarah has prepared a bunch of practice problems for you, so that you get more exercises that involve making these kinds of decisions. Have fun.

Practice With Relational Operators

Cay and I are in a twitter battle. I claimed that I will always have at least one more twitter follower than he has. In other words, my number of twitter followers will always be greater than or equal to the number that Cay has plus one. Is this true, if Cay has three followers and I have a four. What about this statement that Cay plus one is greater than or equal to Sara. How about the statement Cay plus one does not equal Sara?

Practice With Relational Operators

It's true that three plus one is than or equal to four. It's also true that three plus one is greater than or equal to four, but it's not true that three plus one is not equal to four. These values are right on the boundary. We would call this an edge case for this condtion. Its right at the edge of the values that make the condition true or false. When you're writing conditions its really easy to make little slips. Especially for the values right on the edge of the range we want. Its wise to always test a couple of values like this. That way if you miscategorize the case right on the edge you'll find out about it soon. And be able to fix it.

Practice With Relational Operators Part 2

What is the opposite condition of cay plus 1 is less than or equal to sara? Write a condition that's the opposite of cay plus 1 is less that or equal to sara. So, a condition that's true when this one is false, and false when this one is true. Do the same for these other two conditions as well.

Practice With Relational Operators Part 2

The opposite of cay plus 1 is less than or equal to sara is cay plus 1 is greater than sara. The opposite of cay plus 1 is greater than or equal to sara is cay plus 1 is less than sara. And the opposite of cay plus 1 is not equal to sara is cay plus one equals equals to sara. You may have thought that the opposite cay plus 1 is less than or equals to sara should be cay plus 1 is greater than or equals to sara. But the opposite value has to disagree every possible value of cay and sara. Let's look at a representative set of example's. Our original expression was cay plus 1 is less than or equals to sara. We found that when Cay has 3 Twitter followers and Sara has 4 Twitter followers, that's the boundary. So, I'm using that case and two cases, one on each side of that boundary to compare these three conditions to see which ones are opposites. When cay has 3 and sara has 3, it's not true that cay plus one is less than or equal to sara. When cay has 3, and I have 4, this condition's true. When cay has 3 and I have 5, the condition is still true. Now for the next condition, we find that they disagree on conditions that are not right on the boundary. But, right on the boundary, they agree. So these conditions are not opposites. But this last condition is true for the first case, false for the boundary case and false for the last case. So, it differs in every case from the original condition. You could write out similar tables for the other two original equations, but I think this is enough writing tables for now.

Cutest Kitten

Next, we're going to write a kitten class that calculates the cuteness based on a kitten's age. We'll say that kittens over six months old are cute. We'll say that kittens between two and six months, including exactly two months and exactly six months, are super cute. And kittens under two months old are not quite cute yet. They're still too young and sort of look like aliens. There's some code for the kitten class to get you started. You should implement the gate cuteness method and write a tester to make sure your cuteness calculation works for some representative examples.

Cutest Kitten

Before I implement the method, I'm going to write the tester. There are multiple ways you could do this, but there are also a lot of ways that look similar and don't work. Here's the way I came up with. First, it checks to see if the kitten is more than 6 months. If so, we know that we want to return cute. Now, if the kitten is not more than 6 months, but is 2 or more months. Then the kitten is super cute. This condition is only checked if this condition already failed. This whole piece of code is under the else clause for the first if. Now if both of these conditions are false. Then we end up in the last else clause. This catches everything that doesn't satisfy one of the first two conditions. So, if the kitten's not older than 6 months, and is not 2 months or older. Then it's younger than two months, and so it's not cute yet. Let's check that this works. Okay, it looks like these match, they match, match, match and match. So, we're good. We could change this code slightly by adding another condition here. The code will still work modified this way, but it's considered bad form. If you decide to modify the 2 months threshold. You now have to change it in two places instead of just one. Also, if you don't understand the condition right, or just make a little error, there could be cases that you miss and don't handle at all. So, don't add an if condition here. That would be a bug. What if we changed the order of these checks? So, I take months greater than 6 and put it here. Months greater than or equal to 2, here, and then, change the return values to match. Do you think this still works? Lets try it. It looks like it's wrong for the first case. These cases are okay and this one is, but it looks like there aren't any cute kittens anymore. Only super cute ones and not so cute ones. A kitten with eight months will do the first check and find that it's true and return super cute, without ever testing to see if it's more than six months, as well. No matter what number months starts out as, this piece of code, here, will never run. That's a bug.

The Cutest Kitten

What if I add a line to the bottom of this program? What do you think will happen if I try to compile this code and run it? Will the code compile? Will there be an error? What age of kitten would trigger this return statement? Let's try it, the code won't compile. It says unreachable statement. Every possible branch of this if else statement has a return statement already. Once it returns the answer it won't do anymore. It'll exit the method. Even if there might be more code further down. Java can recognize certain situations where there might be unreachable code and it warns you because unreachable code is a mistake. When I write this line, I'm coding for a case that can never happen. All the cases are handled and finished in the if else statement. The else picks up all of the left overs. So, I shouldn't have an extra line at the end of my program that pretends it might return the cutest kitten of all..

What Do You Think Of This Code

Here's another example of an if statement. What would you say about this piece of code? Would you say the conditions are in the wrong order? the if price if less than or equal to 100 should be if price is less than 100, there shouldn't be if price is less than or equal to 100 at all, or there is nothing wrong?

What Do You Think Of This Code

The answer is, there shouldn't be, if price is less or equal to 100. This condition doesn't change the execution. But it adds unnecessary code, and opportunities for bugs. We could later decide that we want to change the threshold of 100. And then we would have to remember to change it in both places. We're creating extra work and unnecessary complexity for ourselves by adding unnecessary code.