Lecture Date: Friday, February 12
Programs that start and then end without any choices to make are boring. If we are going to write a program to do anything interesting, it has to be able to make decisions based on the data it is seeing.
Consider this situation:
Pretty straight forward. But how do we make the computer do something different based on the input?
First, how do we decide whether it is cold outside or not?
Well, we could ask the user:
This is good, but this doesn’t yet tell us whether it is specifically cold or not. And that’s different for everyone. So let’s add this:
So, now let’s test whether it is cold or not!
1 2 3 4
There’s another way we could do this - and that’s with what’s called a flag variable. A flag variable is a
bool that we use to determine some sort of state. In this case, we would write it like this:
1 2 3 4 5 6 7 8 9 10 11
This makes the code a bit more readable, and
is_cold can be easily reused later on.
Now, what if we had to make more of a decision here:
We could use our flag variable again, but now we will add another option to our
1 2 3 4 5 6 7 8 9 10
In this case, we must do one or the other. A simple
if statement either will or will not execute. Here, if the
if is not executed, then the
else will be.
We can string more of these together as well!
1 2 3 4 5 6 7 8
Now you are guaranteed to execute one of these three paths.
Other points for today:
- How to indent your code properly
- Relational operators (<, >, ==, >=, <=, !=)
- How to test for your letter grade in the class