Branching

Table of Contents

c1_u05_Branching_controlflow.png


Branching is one of the core forms of controlling the flow of the program. We ask a question, and based on the result we perhaps do this code over here or maybe that code over there - the program results change based on the variable values.


1. Boolean expressions

A boolean expression is a statement that is either true or false. You can think of "yes/no" questions as being built off of a boolean expression. For example:

Boolean expression Question form
This document is in English. Is this document in English?
The year is 1950. Is the year 1950?
The sky is lime green. Is the sky lime green?

This is how computers ask questions in the program code - a series of yes/no questions, and special instructions for each outcome.

1.1. Relational operators (greater than, less than, equal to)

One of the main ways we build "yes/no" questions in our code is to use relational operators to compare values, such as "greater than", "less than", "equal to", and more…

Comparison Relational operator Example
Is a equal to b? == a == b
Is a not equal to b? != a != b
Is a greater than b? > a > b
Is a greater than or equal to b? >= a >= b
Is a less than b? < a < b
Is a less than or equal to b? <= a <= b

1.2. Logic operators (and, or, not)

We can also combine multiple boolean expressions together to ask a single question with several parts. We can combine sub-expressions together using and and or operators, or we can negate the result using the not operator.

In Python, we use the keywords and, or, and not.

In C++, we use the operators && for and, || for or, and ! for not.

Python
if ( a >= min and a <= max ):
    valid_input = True

if ( a < min or a > max ):
    valid_input = False

if ( not ( breakfast or lunch or dinner ) ):
    can_eat = False

C++
if ( a >= min && a <= max )
{
    valid_input = true;
}

if ( a < min || a > max )
{
    valid_input = false;
}

if ( !( breakfat || lunch || dinner ) )
{
    can_eat = false;
}

1.3. What do we compare?

The main data types we work with in our programs are numbers, strings (text), and booleans. With numbers, we might check if two things are equal, or one is greater than another, and so on. We can also do these comparisons on strings. With booleans, we're usually just checking if the variable is storing true or false as a value.

Data type Example Explanation
Numbers a > 10 Is a greater than 10?
Strings name1 < name2 Does name1 come before name2 in the alphabet?
Boolean game_saved Does the variable have a true value?
Boolean !game_saved Does the variable have a false value? (C++)

2. If statements

If statements (usually the general term encompassing if / else if / else as well) are a way we can ask a question and respond: If a is less than b then… or if a is greater than c then… Otherwise do this default thing…

The form of an if statement is…

command1
command2

if ( CONDITION )
  command x

command3

Our program is going along running commands 1 and 2. Then, we encounter a question. If the condition is true, then the special command x is executed, before we continue on with command 3. If, however, the condition is false, then we skip the special command x and go from command 2 to command 3.

An if statement will look a little different based on the programming language, but how it works remains the same.

Python
balance = float( input( "What is your bank balance? " ) )
print( "Bank balance is: $", balance )

if ( balance < 0 ):
    print( "OVERDRAWN!" )

print( "Thank you for using Bank" )
C++
cout << "What is your bank balance? ";
float balance;
cin >> balance;
cout << "Bank balance is: $" << balance << endl;

if ( balance < 0 )
{
  cout << "OVERDRAWN!" << endl;
}

cout << "Thank you for using Bank" << endl;

The condition for these if statements is "is balance less than 0?" - this is a question that will either result in yes (true) or no (false). Then, we have a code block that belongs to the if statement. The code within this code block is only executed if the condition evaluates to true.

  • Adding an if statement allows us to execute some special code only if some condition is met.
  • If that condition evaluates to false, then the if statement's codeblock is skipped.

Python
An if statement ends with a colon : and anything INSIDE the code block is tabbed forward by 1 tab. Code that retursn to the original tab position is AFTER the code block.
statement
statement

if ( CONDITION ):
    condition_true_inside_statement
    condition_true_inside_statement

statement
statement
C++
With C++, a code block begins at the opening curly brace { and ends at the closing curly brace }:
statement
statement

if ( CONDITION )
{
    condition_true_inside_statement
    condition_true_inside_statement
}

statement
statement

c1_u05_Branching_if.png


3. If/else statements

An if statement only executes special commands if a condition is met, and otherwise skips over that code block. With an if/else statement, we can specify special code for when the condition is true or when the condition is false, so that one of the two instruction sets are executed before continuing on in the program.

  • The else statement is executed when the if statement's CONDITION evaluate to false.
  • This is usually a way to have some "default" functionality if the if statement doesn't get triggered.
  • Note that else statements DO NOT HAVE A CONDITION, so no ( CONDTIION ) portion!

Python
statement
statement

if ( CONDITION ):
    condition_true_inside_statement
    condition_true_inside_statement

else:
    condition_false_inside_statement
    condition_false_inside_statement

statement
statement
C++
statement
statement

if ( CONDITION )
{
    condition_true_inside_statement
    condition_true_inside_statement
}
else
{
    condition_false_inside_statement
    condition_false_inside_statement
}

statement
statement

c1_u05_Branching_ifelse.png


4. If/else if/else statements

Adding else if statements after our initial if statement allows us to check for several different conditions in a row. When we're writing a series of if/else if statements, their conditions should be related (such as "is it breakfast time? No. OK, is it lunch time? No. OK, is it dinner time?"), and an optional else case can be added at the end as the "catch-all" if all other conditions above fail.

  • if/else if statements are a way we can check for multiple conditions, one after another.
  • The if condition is always evaluated FIRST, with each subsequent else if condition being evaluated in order (from top-to-bottom).
  • The else case is optional and can be left off if desired.
  • The else case gets executed if all if and else if statements' conditions evaluated to false.
  • Note that Python uses "elif" and C++ uses "else if".

Python
statement
statement

if ( CONDITION ):
    condition_true_inside_statement
    condition_true_inside_statement

elif ( CONDITION2 ):
    condition2_true_inside_statement
    condition2_true_inside_statement

elif ( CONDITION3 ):
    condition3_true_inside_statement
    condition3_true_inside_statement

else:
    all_conditions_false_inside_statement
    all_conditions_false_inside_statement

statement
statement
C++
statement
statement

if ( CONDITION )
{
    condition_true_inside_statement
    condition_true_inside_statement
}
else if ( CONDITION2 )
{
    condition2_true_inside_statement
    condition2_true_inside_statement
}
else if ( CONDITION3 )
{
    condition3_true_inside_statement
    condition3_true_inside_statement
}
else
{
    all_conditions_false_inside_statement
    all_conditions_false_inside_statement
}

statement
statement

c1_u05_Branching_ifelseif.png


5. Example programs

If statement:

Python
balance = float( input( "Enter bank balance: " ) )

if ( balance < 0 ):
    print( "Overdrawn!" )

print( "Goodbye" )

C++
float balance;
cout << "Enter bank balance: ";
cin >> balance;

if ( balance < 0 )
{
  cout << "Overdrawn!" << endl;
}

cout << "Goodbye" << endl;

If/else statement:

Python
balance = float( input( "Enter bank balance: " ) )

if ( balance < 0 ):
    print( "Overdrawn!" )

else:
    print( "You're all good!" )

print( "Goodbye" )

C++
float balance;
cout << "Enter bank balance: ";
cin >> balance;

if ( balance < 0 )
{
  cout << "Overdrawn!" << endl;
}
else
{
  cout << "You're all good!" << endl;
}

cout << "Goodbye" << endl;

If/else if statement:

Python
balance_chk = float( input( "Enter checking $: " ) )
balance_sav = float( input( "Enter savings $: " ) )

if ( balance_chk + balance_sav < 0 ):
    print( "You are in debt!" )

elif ( balance_chk + balance_sav == 0 ):
    print( "You have NO MONEY!" )

else:
    print( "You're all good!" )

print( "Goodbye" )

C++
float balance_chk, balance_sav;
cout << "Enter checking $: ";
cin >> balance_chk;

cout << "Enter savings $: ";
cin >> balance_sav;

if ( balance_chk + balance_sav < 0 )
{
  cout << "You are in debt!" << endl;
}
else if ( balance_chk + balance_sav == 0 )
{
  cout << "You have NO MONEY!" << endl;
}
else
{
  cout << "You're all good!" << endl;
}

cout << "Goodbye" << endl;

Author: Rachel Wil Sha Singh

Created: 2023-09-29 Fri 17:00

Validate