Comp 110 if-then & if-then-else Statement

if-then Statement Syntax

Often while programming, we will want blocks of code to only run some of the time. To accomplish this, we can use if-then statements. If-then statements an be written anywhere you can write a statement. An if-then statement evaluates an expression to a boolean value to determine if the code is executed, as illustrated below.

if (<boolean condition>) {
  <then block>
}

If the boolean condition is true, then the block will execute. Otherwise, the block is skipped and the program continues running after it. It is important to understand that the boolean condition can be written in many different ways, as long as it evaluates to either true or false.

if-then-else Statement Syntax

Sometimes while programming we will want one of two blocks of code to run every time. To accomplish this, we can use if-then-else statements. An if-else statement evaluates an expression to a boolean value to determine which of the two blocks of code is executed, as illustrated below.

if (<boolean condition>) {
  <then block>
} else {
  <else block>
}

Just as with the if-then statement, if the boolean condition is true, then the first block will execute. However, if the boolean condition is false, the entire block is not skipped, but rather, the code will skip over the first block of code to the second block. Upon executing the second block of code, the program will continue running.

It is important to remember that with an if-then-else statement the second block of code will be executed every time the boolean is false. If we do not want the second block of code reached every time, we should consider writing an if-then statement instead, or using the else-if syntax trick.

For a better understanding of boolean conditions and what can work, check out Boolean Operators.