Computer Science Canada If Statements |
Author: | Cervantes [ Fri Dec 29, 2006 6:57 pm ] | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Post subject: | If Statements | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
If Statements
Introduction
In computer science, much like in the English language, if statements are used to make decisions. For example, "if I have $2.95 on me, then I'm going to buy a slice of pepperoni pizza from the caf." We're going to take this English statement and migrate into Turing code. This tutorial aims to teach the semantics of if statements in Turing. We'll lay down some basic rules about the syntax of Turing and from there we will develop a system that allows us to evaluate code in a stepwise manner. In general, an if statement in Turing looks like the following:
Now, I will lay down two fundamental rules. Assume "<action>" is some Turing code. It could be one line long, or more.
That is, the action in code (a) is never executed. Now, we can write code that matches the code patterns in these two rules, but that won't be very helpful to us. It won't be helpful because this code is as static as the code we could write previously. We still aren't making any decisions. To do this, we need to learn about expressions. I will define an expression, in a kind of wishy-washy way, as anything that can be evaluated, simplified, or reduced down to a value. Values are concrete things: numbers like 5.8, strings like "hello world", true, and false. A mathematical expression such as "5 + 3 / 4" is an expression, because it can be simplified down to a value: 5.75. Here's another example, involving variables:
Evaluating the second line of code is not a one step process. Because "my_money" is an expression, we must first substitute in our value for the "my_money" expression. So the first step in evaluating this would be the following:
And then the second line of code can be taken care of by a special rule in Turing's syntax that says "put <value>" can be handled. We've now encountered one type of expression: a variable that is bound to some value. However, we still aren't able to write dynamic code--code that makes decisions. We have to look at some more complex expressions, expressions that use "operators". Expressions using Operators In computer science, an operator is something that is placed between two "operands". Operands are things like numbers or strings or other data. An operator compares the data on its left to the data on its right and returns a value. Some common operators are equals ("="), and ("&"), or ("|"), greater than (">"), less than ("<"), greater than or equal to (">="), and less than or equal to ("<="). All this should be fairly intuitive. Here are some examples:
This expression uses the "&" operator to compare the two operands, (1) true and (2) false. It returns false, since & returns true if and only if both operands are true, as is intuitive.
Here, the "=" operator cannot be immediately evaluated. This is because its first operand is not yet a value, but rather an expression itself. In a stepwise evaluation of this code, the next step would be to substitute the value for "my_money", to get the following:
Now the "=" operator does its work, comparing 2.95 to 2.95, and it finds that these are equal, so it returns true. In the stepwise evaluation, the next step is this:
And this outputs "true".
Here, the "&" operator cannot do its work right away, since its left operand is an expression. Let's go through a stepwise evaluation of this expression:
You'll notice that the expression "(false | true)" evaluated to true. This is because the or ("|") operator returns true if at least one of its operands is true. Another way of saying this is that the or ("|") operator returns false if and only if both its operands are false. Now we know how to simplify expressions. With this new skill, we can use expressions as conditionals to decide whether to perform certain actions or not. Let's now return to the pizza purchasing example presented at the start of this tutorial. We're finally able to code it. An example using what we've learned so far I'll reiterate the example we're going to express in Turing code. It goes like this: I need to decide what I'm having for lunch. If I've got $2.95 or more on my person, I'll buy myself a slice of pizza. In Turing code, this looks like the following:
The "my_money" variable represents the state of me. It represents how much money I have on my person. Let's step through the execution of this code:
And now we are on familiar ground. I chose 3.70 arbitrarily as the amount of money I have on my person. You can put a different value into the code and you might get a different result. If the value you use is less than 2.95, the code inside the if statement will never be executed and you won't get any output, and the value of my_money will not be changed. So we've successfully created code that makes a decision! It works differently depending on the state of the program--the values of the variables. Now I raise the question, "What should I do if I don't have $2.95 or more on my person? I'm going to starve, surely!" This is the otherwise, or "else", case. Else If at lunchtime I didn't have enough money to buy a slice of pizza, I'd probably ask my friends to buy me a slice of pizza. I just gotta have my pizza, you know. Let's incorporate that declaration of my behaviour into our example, and code it.
Now, this seems a little unnecessary, don't you think? I'm going to trace through this code, and it's a little bit long, but nothing difficult. If the value of "my_money" is less than 2.95, then our trace of the code would look like this:
And now we have simplified our code down to a point where it is static--no more if statements. In our trace, we had to determine the value of the expression "my_money >= 2.95". We determined this to be false. Since the value of "my_money" is not changed anywhere between the time that we test "my_money >= 2.95" and the time that we test "my_money < 2.95", we know that the second expression, "my_money < 2.95" evaluates to true, since it is the opposite of "my_money >= 2.95" and that expression evaluated to false. So, we shouldn't have to go through the work of comparing "my_money" to 2.95 again, should we? To solve this problem, we'll add to our syntax. I will now introduce two new rules, just like I gave two rules at the start of this tutorial. Assume <action1> and <action2> are two distinct bits of Turing code.
With these new semantics, we can now rewrite the pizza example:
Try going through the trace of this in your head. You'll notice I didn't bother with two variables I had in the previous code: "my_order" and "friends_order". I needed those in the previous code because, unlike when using else, doing the action in the first if statement did not prevent doing the action in the second if statement. So pictures this, in your mind's eye: I write the code that started this section (the one with my_order and friends_order) except I don't use those two variables. Instead, inside the first if statement that tested "my_month >= 2.95", I just decrease my_money by 2.95, then and there. Well then, what would have happened if I had $4.00 on my person? The first expression, "my_money >= 2.95", would be true, so we would execute the code inside that if statement. That would decrease the value of my_money by 2.95, leaving me with $1.05. That's less than $2.95, so when I go to test the second expression, it too is true! Thus, I would have entered both if statements, and my speech would have sounded dumb: "I'll buy myself a slice of pizza. Friend, can you buy me a slice of pizza?" To solve this problem I had to carefully avoid modifying the value of my_money until after both if statements; I did that by introducing new variables: my_order and friends_order. By using else, we don't have any of these problems. Question Time: Write a program that gets two numbers from the user and determines whether the first number is bigger than, equal to, or less than the second number. A solution to this problem is found at the end of this tutorial. I suggest you try solving it for yourself before peeking, though. That's how you learn best. Now I'm going to make the situation in the caf more complicated. |
Author: | Cervantes [ Fri Dec 29, 2006 6:58 pm ] | ||||||||||||||||||||||||||||||||
Post subject: | |||||||||||||||||||||||||||||||||
Many related choices: Elsif
If I've got $2.95 or more on my person, I'm getting a slice of pepperoni pizza. That's my primary choice, for certain. But what if I don't have enough for a pizza, but I do have enough for a bagel, which costs $1.00? I should get the bagel, right? And if I don't even have enough for a begal, then I'll ask my friends to buy me a begal. One way to code this is like so:
This works, but again, it's inefficient. For one, I had to do the business with my_order and friends_order. More importantly, we're doing more tests on "my_money" than we need to. Can you see why? The reasons are the same as in the previous example when I introduced "else". Try doing a trace of it in your head. To fix this, I'll introduce two new rules.
With these new rules, we can rewrite the pizza and begal example:
Notice, once again, that I didn't have to bother with my_order or friends_order. Now, I'll do a trace on this. It will be rather long, but it's worthwhile, because being able to trace through a program properly is crucial when debugging. Here's the trace:
And now we're on familiar ground. Question Time: Write a program that gets three numbers from the user and determines the value of the largest number. A solution to this problem is found at the end of this tutorial Conclusion By now, you should be able to write dynamic programs--programs that can make decisions. You can execute different bits of code depending on what state your program is in. This is vital. As you continue to learn about Turing and about computer science in general, you will continue to see if statements making their presence known. Also, this tutorial taught some basic semantics of Turing. These are the rules by which a Turing program can be traced and clarity made of otherwise confusing code. The ability to trace code is essential when trying to understand code. The code may or may not be your own. You might be trying to debug your code or trying to understand someone else's code. Regardless, tracing code is a fundamental tool that you will need. Solutions Here are possible solutions to the two problems given in this tutorial.
Disclaimer: Actual price of slice of pepperoni pizza may vary. My caf sucks, except for the breakfast special. |
Author: | Hackmaster [ Fri Dec 29, 2006 7:30 pm ] |
Post subject: | |
Cervantes! yet another awe-inspiring tutorial! glad you got this one out! keep up the good work!! |
Author: | zylum [ Thu Jan 04, 2007 3:08 am ] | ||
Post subject: | |||
very nice you might want to add the xor operator though:
|
Author: | Cervantes [ Thu Jan 04, 2007 1:59 pm ] |
Post subject: | |
I was thinking about it, but I figured that won't be of any immediate use. Your bitwise operators tutorial handles it, I think. |
Author: | Megatokyoguy [ Mon May 14, 2007 9:01 am ] |
Post subject: | RE:If Statements |
I am currently working on Turing in class and I loved your previous tutorial (even though I know all that already - I am trying to learn about making games because I have a program that came with turing but I do not understand all the components) I don't get the "Expressions using Operators" Very confusing for me..... |
Author: | Cervantes [ Mon May 14, 2007 11:11 pm ] |
Post subject: | RE:If Statements |
Can you be more specific about what you didn't understand? Really, it shouldn't be hard stuff. If you have any experience with basic math, this section should come pretty naturally. If give me some specifics, though, I'll gladly help you out. |
Author: | bawler27 [ Sat Mar 08, 2008 7:52 pm ] |
Post subject: | Re: If Statements |
nice tut, it helped me out alot! now i can understand half the programs on the forums but there is one thing bothering me. there was this one program that used var+=var what does that mean or do? |
Author: | Mackie [ Sat Mar 08, 2008 8:12 pm ] |
Post subject: | RE:If Statements |
var += var Is the same as var := var + var But, a better example would be. a += b a := a + b There are others as well. a -= b a /= b a *= b a div= b a mod= b |
Author: | Sean [ Sat Mar 08, 2008 10:01 pm ] | ||
Post subject: | Re: If Statements | ||
if you were doing var += var then you are just adding the variable to itself, but you could do..
Which increases the variable by 2, instead of increasing it by itself. |
Author: | bawler27 [ Sun Mar 09, 2008 9:28 am ] |
Post subject: | Re: If Statements |
oh, it all makes sense now, thx alot guys !!! |