Conditionals

:

Articles

Some IFs, no ANDs, ORs, or BUTs about it...


    Note: This is a multi-part article was written for programmers of varying experience. Part 1 was written for those with little to no prior programming knowledge. You may find some content redundant to your knowledge, but stick around anyway... you might just learn something new.

    

What the heck is a conditional?

A conditional allows you to evaluate a statement as True or False, and then act based on that evaluation. In other words, it allows you to act based on a condition. Many constructs use conditional statements to determine their next course of action. These include if statements, while loops, for loops, and others depending on the language (like the do... while loop, for example).

That's great, but how can I use it?

Let's write an if statement in human terms first. To start, all we're doing is, essentially, asking a question. Is this thing true? If it is, I want to do one thing. Otherwise, I want to do another. Let's look at a real-life example. In this example, there are two different routes you can take to work. You can take the freeway, or you can take the back roads. The freeway is typically faster, except when there is traffic. So, in human terms:

If there is traffic, take the back roads;
Otherwise, take the freeway; (obligatory semicolons)
        
Simple enough. Now, you don't want to check the traffic cameras every morning to find out if there's traffic - that's too much work. You're a programmer. Your job is to do it once, and let the computer do it for you from then on out. You've done some googling, and found someone else wrote a bunch of code that looks at traffic cameras and tells you how many cars are on the freeway at any given time. It even stores it into a variable for you called cars. Huzzah! Now, all you need to do is do something with that information. When we write an if statement, we're checking to see if a certain condition is True. The simplest if statement we can possibly write is this:

# Python
if True:
  print("it is true")
          

//C++
if (true) {
  printf("it is true");
}
          
That is, in the end, what an if statement is looking for. True or False. Now before we start shoving conditionals in every nook and cranny, let's look at a conditional outside of an if statement.

# Python
b = 1 > 0
print(b) # output is "True"
          

//C++
bool b = 1 > 0;
printf("%d", b); //output is "1"
          
There are a few odd things about C that I'd like to address before we continue. C++ does not have a boolean print format specificier. A boolean is a type that can be True or False, and only True or False. Think about how an integer (seen as int in most programming languages) is - and I want to emphasize that I'm grossly oversimplifying for the sake of explanation - a counting number. In programming, it's a 32-bit counting number in the range [-1 * 2^31, 2^31 - 1]. So, where an int is any counting number from –2147483648 up to 2147483647, a bool is either 0, or 1. C++, however, does have a boolean type, and it can be defined with the keyword bool. For Arduino, you can use C++ to make your life a bit easier. In my (albeit limited) experience, most C code will run in C++. YMMV. Note: in many languages, most basic types can be converted to a bool. For integers, 0 is False, all other numbers are True. For strings, an empty string, "", is False, and anything else is True. Try it out! C also has a somewhat unique print function compared to newer languages. We use the % sign to define a data type to print (in this case, %d for decimal), and afterwards we include the value to print. Just something to keep in mind. In our example above, we defined the variable b as being equal to "1 > 0". Our compiler recognizes that 1 > 0 is a conditional statement, and tests to see if it is True. Lucky for us, we happen to know that 1 is in fact greater than 0. Our compiler also sees this. In the case of Python (and most languages), it stores the value True in the variable b. In the case of C, it would store the value 1 in the variable b, because in C (and almost ALL languages) 1 and True are the same thing. Note: There is a difference between True and "True". The first is a boolean, the second is a string. In our case, we are referring to the boolean.

Get to the point. How do I use it to control the world?

Right. I'm not sure about that, but at the very least we can try to solve our current problem. Let's write a conditional to check if there is traffic on the freeway.

# Python
traffic = cars > 100
if traffic:
  print("Take the back roads.")
      

//C++
int traffic = cars > 100;
if (traffic) {
  printf("Take the back roads");
}
          
Remember, we copied some code online to store the number of cars on the road to the variable cars. Or at least, hypothetically we did. In this example, we're assuming the variable cars is some integer value. We're checking to see if there are more than 100 cars on the road - if there are, traffic is probably going to slow us down and we'll take the back roads.

And if there's no traffic, it says... nothing? Your program is bad and you should feel bad.

I was getting there :( Right now, our program checks to see if there is traffic, and if there is, it tells us to take the back roads. But it would probably be a little more user-friendly if it told us when to take the freeway, wouldn't it? Let's think about what we know. There are two ways to get to work - the freeway, and the back roads. We have to take one of them. If we're not taking the freeway, we're taking the back roads (which we've already programmed). Likewise, if we're not taking the back roads, we're taking the freeway - in other words, otherwise take the freeway. We can add this functionality in as an else statement.

# Python
traffic = cars > 100
if traffic:
  print("Take the back roads.")
else:
  print("Take the freeway.")
      

//C++
int traffic = cars > 100;
if (traffic) {
  printf("Take the back roads");
} else {
  printf("Take the freeway");
}
          
Easy enough. As programmers, we're always looking to do more with less... in other words, we want to type as little as possible. Right now, we're defining a boolean variable to hold True if there is traffic, and False if there isn't. But we don't need to do that - we can do it all within the if statement.

# Python
if cars > 100:
  

//C++
if (cars > 100) {
            
This has the same effect, but shortens our code by a line. Let's assume for the sake of example, that cars = 150. Then, the statement cars > 100 is True. It is interchangeable with True. True is cars > 100, and cars > 100 is True. They mean the exact. same. thing. Sometimes you'll be able to put arguments on the same line, and sometimes you won't. Use whichever method you are most comfortable with.

1 2