CIUC- Conditionals: if, else, and else if Lesson

Conditionals: if, else, and else if

Conditional expressions are one of the most important components of programming languages because they enable a program to act differently each time it is executed, depending on the input. The process of ordering that determines the program's flow of control is referred to as branching.  

Branching is also referred to as conditional programming and is the process of creating code that has the ability to change paths based on a set of conditions stipulated in the program or influenced by user interaction.    

The conditional statement is a single statement that checks a condition. Conditionals are also called decision statements or selection statements.

An if statement is the basic structure used for conditional programming. There are three different ways to structure an if statement. Examine each of the structures below and observe the correct syntax.  

ifstructure if ( boolean expression) 
{
// code to do something if true }

 

If else if structure 
if ( boolean expression)

Multiple conditions require an appropriate Boolean logic operator. Notice you must have a full condition on each side of the Boolean operator.

boolean logic operator OR is used when you want either condition to be true in order to execute.

boolean logic operator AND  is used when you want either  two condition to be true in order to execute.

It is important to notice in the examples above that every open brace { must have a matching closing brace }. If you do not have a matching open/close brace you will get an error message.

When an if statement block only has one statement, it does not require a beginning or closing brace. When the statement block has more than one statement it is necessary to have the beginning and closing braces to specify where the block starts and where it ends.

If Structure and If Else If Videos

Watch the if structure video below.

Watch the if else if video below.

Structures of an If Statement Activity

Click through the presentation below to learn about the Structures of an If Statement.

[CC BY 4.0] UNLESS OTHERWISE NOTED | IMAGES: LICENSED AND USED ACCORDING TO TERMS OF SUBSCRIPTION