If Statements
Control the flow of your code by using If Statements

 

What are If Statements?

If statements let our code make decisions. We use them all the time in our lives. If I am hungry then I will get some food. If it is sunny outside then I will play outside. These are two examples of these decisions. Of course some decision are more complex than that. In programming they work about the same:

The condition (in side of the parentheses) is the if part, and then inside of the curly brackets is the then part. So our first one would look like this:

However if we try to run this code it would not work, so lets do an actual program using variables (if you want to learn more about variables, checkout this page). We will create a variable A and see if it is larger than 10, if it is we will set it to 10.

Now we will add in an else statement, these ones happen if the if part is false:

So our code could look like this:

And we can even combine them together into an else if statement:

So if A is greater than 10 it will equal 10, if it is not greater than 10 and less than 5 it will equal 1, and if it is not greater than 10 and not less than 5 it will equal 9.

For the conditions you have several comparison options:

  • Greater than: >
  • Less than: <
  • Greater than or equal to: >=
  • Less than or equal to: <=
  • Equal to: ==
  • Not equal to: !=

So here is a full code we can try out.

Then when we run this code it should output:

A = 1
A = 3
A = 4
A = 5
A = 6
A = 7
A = 8
A = 9
A = 10
A = 11
A = 0
A = 1
A = 3
A = 4

……

Since the first time through A is 1, it will go to the else if part, thus A will be 3. Then it keeps adding one to A until it is greater then 10, in this case once A = 11, then it will set A to 0. Then it repeats the cycle over again.