Logic & Control Structures

"Logic and control structures are fundamental building blocks of programming that dictate the order in which instructions are executed. Sequential execution follows statements in a linear order. Decision structures (e.g., if-else statements) allow for conditional branching based on specific conditions. Repetition structures (e.g., loops) enable repeated execution of code blocks until a certain condition is met. These structures work together to create programs that can perform complex tasks and make intelligent decisions."- Gemini 2024

There are 3 main types of control structures: sequential, selection, repetition. In programming languages, these control structures dictate program flow.

flowchart diagrams of 3 control structures

Sequential execution is straight forward. Execute a command, go to the next, execute that, and so on. Both selection and repetition require a conditional expression to make a decision about which command(s) to execute next.

Conditional Logic

Conditional logic expressions are used to make decisions. These are boolean expressions, meaning that they evaluate to true or false. Boolean expressions can be built using boolean logic.

These kinds of expressions appear in numerous fields of study, including philosophy of logic, boolean algebra, set theory, database search queries, digital circuit design, electronics engineering, linguistics, and extensively throughout subfields of artificial intelligence. In fact, boolean expressions are not just present in AI but are deeply integrated within various subfields like machine learning, natural language processing, and robotics.

Decision-making with boolean conditions

Boolean expressions are created using the terms and, or, and not. These terms are represented by different symbols depending on the field of study, but carry identical, or nearly identical meaning.

Term Symbols
AND
&  &&  ·  ∧  and
OR
|  ||  +  ∨  or
NOT
  !    ~  ¬  not
3 logic gates: and, or, not
A B AND
True True True
True False False
False True False
False False False

AND Truth Table

A B OR
True True True
True False True
False True True
False False False

OR Truth Table

A NOT
True False
False True

NOT Truth Table

Example Boolean Expression

In the board game Zombicide, a survivor can only safely attack a zombie in the room if one of these conditions is true:

  1. The survivor has a melee weapon
  2. The survivor has a ranged weapon with range 0 and there are no other survivors in the room

To create this conditional expression, let

  • Z = "There is a zombie in the room"
  • M = "The survivor is holding a melee weapon"
  • R = "The survivor is holding a ranged weapon with range 0"
  • S = "There is another survivor in the room"
Then, the boolean expression is

Z & M | Z & R & !S

Order of Operations = NOT, AND, OR
In boolean logic, NOT is evaluated first, followed by AND, and then OR, with parentheses overriding this order.
Short Circuit Evaluation

Short-circuit evaluation is an optimization technique used in some programming languages for evaluating logical expressions with the AND (&&) and OR (||) operators. It involves stopping the evaluation of the next operand as soon as the overall result can be determined.

For example:

Not all programming languages implement short-circuit evaluation. However, it's a common feature in languages like C, C++, Java, and Python.

Control Structures

Now that we have a conditional expression, we can create control structures with it.
Selection
Repetition

Beware of infinite loops using while constructs, always ensure a stopping condition will eventually be met.

Code Examples

# SELECTION

# if statements

count = input('How many rocks do you have? ')
count = int(count)

if count <= 2:
    print('I can carry those in my hands')
elif count < 8:
    print(f'I can carry 2 rocks in my hands and {count-2} in my backpack.')
else:
    print('I am a little robot, I cannot carry that many rocks.')

# ternary operator

food = input('Is this food? ')

able = 'can' if food.lower().startswith('y') else 'cannot'
print(f'I {able} eat this.')

# switch/case statement (Python >= 3.10)

season = input('What season is it? ').lower()

match season:
    case 'winter':
        print('I do not like the cold.')
    case 'spring':
        print('I want to go to the park.')
    case 'summer':
        print('Please do not let me fall in the pool again.')
    case 'fall':
        print('Can I be a cat for Halloween?')
    case _:
        print('I do not know that season.')

# REPETITION

# while loop

x = 3

while x > 0:
    print('While loop', x)
    x -= 1

# do while loop (emulated in Python)

playing = True

while playing:
    song = input('What do you want to hear? ')
    if song.lower() == 'stop':
        playing = False
    else:
        print(f'Now playing {song}')

# for loop to run n times

n = 5
for i in range(n):
    print('for loop', i)

# for loop over list/array

name = input('What is your name? ')

print('Here is your name in a unicode binary block:')
for char in name:
    code = ord(char)
    print(f'{code:08b}')

# list comprehension in Python

print('Here is your name in a unicode binary block:')
bits = [f'{ord(x):08b}' for x in name]
print('\n'.join(bits))

            
// SELECTION

// if statements

let count = parseInt(prompt('How many rocks do you have? '));

if(count <= 2) {
    console.log('I can carry those in my hands');
}
else if(count < 8) {
    console.log(`I can carry 2 rocks in my hands and ${count - 2} in my backpack.`);
}
else {
    console.log('I am a little robot, I cannot carry that many rocks.');
}

// ternary operator

var food = prompt('Is this food? ');
var able = food.toLowerCase().startsWith('y') ? 'can' : 'cannot';
console.log(`I ${able} eat this.`);

// switch/case statement

var season = prompt('What season is it? ').toLowerCase();

switch (season) {
case 'winter':
    console.log('I do not like the cold.');
    break;
case 'spring':
    console.log('I want to go to the park.');
    break;
case 'summer':
    console.log('Please do not let me fall in the pool again.');
    break;
case 'fall':
    console.log('Can I be a cat for Halloween?');
    break;
default:
    console.log('I do not know that season.');
}

// REPETITION

// while loop

let x = 3;

while(x > 0) {
    console.log('While loop', x);
    x--;
}

// do while loop

let playing = true;

do {
    var song = prompt('What do you want to hear? ');
    if(song.toLowerCase() === 'stop') {
        playing = false;
    }
    else {
        console.log(`Now playing ${song}`);
    }
} while(playing);

// for loop to run n times

var n = 5;

for(let i = 0; i < n; i++) {
    console.log('for loop', i);
}

// for loop over list/array

var name = prompt('What is your name? ');

console.log('Here is your name in a unicode binary block:');
for(var char of name) {
    var code = char.charCodeAt(0).toString(2).padStart(8, '0');
    console.log(code);
}

// map in JavaScript

var bits = name.split('').map(char => char.charCodeAt(0).toString(2).padStart(8, '0'));
console.log('Here is your name in a unicode binary block:');
console.log(bits.join('\n'));

            
// SELECTION

// if statements

Console.WriteLine("How many rocks do you have? ");
int count = int.Parse(Console.ReadLine());

if (count <= 2)
{
    Console.WriteLine("I can carry those in my hands");
}
else if (count < 8)
{
    Console.WriteLine($"I can carry 2 rocks in my hands and {count - 2} in my backpack.");
}
else
{
    Console.WriteLine("I am a little robot, I cannot carry that many rocks.");
}

// ternary operator

Console.WriteLine("Is this food? ");
string food = Console.ReadLine();

string able = food.ToLower().StartsWith('y') ? "can" : "cannot";
Console.WriteLine($"I {able} eat this.");

// switch/case statement

Console.WriteLine("What season is it? ");
string season = Console.ReadLine().ToLower();

switch (season)
{
    case "winter":
        Console.WriteLine("I do not like the cold.");
        break;
    case "spring":
        Console.WriteLine("I want to go to the park.");
        break;
    case "summer":
        Console.WriteLine("Please do not let me fall in the pool again.");
        break;
    case "fall":
        Console.WriteLine("Can I be a cat for Halloween?");
        break;
    default:
        Console.WriteLine("I do not know that season.");
        break;
}

// REPETITION

// while loop

int x = 3;

while (x > 0)
{
    Console.WriteLine("While loop " + x);
    x--;
}

// do while loop

bool playing = true;

do
{
    Console.WriteLine("What do you want to hear? ");
    string song = Console.ReadLine();
    if (song.ToLower() == "stop")
    {
        playing = false;
    }
    else
    {
        Console.WriteLine($"Now playing {song}");
    }
} while (playing);

// for loop to run n times

int n = 5;

for (int i = 0; i < n; i++)
{
    Console.WriteLine("for loop " + i);
}

// for loop over list/array

Console.WriteLine("What is your name? ");
string name = Console.ReadLine();

Console.WriteLine("Here is your name in a unicode binary block:");
foreach (char letter in name)
{
    int code = letter;
    string binaryCode = Convert.ToString(code, 2).PadLeft(8, '0');
    Console.WriteLine(binaryCode);
}

// "list comprehension" in C#

string[] bits = name.Select(letter => Convert.ToString((int)letter, 2).PadLeft(8, '0')).ToArray();
Console.WriteLine("Here is your name in a unicode binary block:");
Console.WriteLine(string.Join("\n", bits));