Operator and Control Flow

1. Welcome and Icebreaker:

Welcome! It’s great to have you back.

If you could design a new control flow structure (something different from if, while, for, etc.), what would it do, and how would it work?

2. Outline the Session:

Here’s our plan:

  1. Concept Explanation: We’ll cover arithmetic, comparison, logical, and assignment operators. Then, we’ll explore if, else if, else, loop, while, and for constructs.
  2. Live Coding Demonstration: We’ll write code examples to see how these operators and control flow structures work in practice.
  3. Tasks: I will challenge you in task section.

Learning Outcomes: By the end of this session, you will be able to:

  • Use arithmetic, comparison, logical, and assignment operators.
  • Write conditional statements using if, else if, and else.
  • Create different types of loops (loop, while, for).
  • Use break and continue to control loop execution.

Expectations: Ask questions whenever you need clarification. Experiment with the code, try different variations, and see what happens!

3. Concept Explanation:

Operators:

  • Arithmetic Operators:
    • + (addition)
    • (subtraction)
    • (multiplication)
    • / (division)
    • % (remainder/modulo)
  • Comparison Operators: These operators compare two values and return a boolean (true or false).
    • == (equal to)
    • != (not equal to)
    • > (greater than)
    • < (less than)
    • >= (greater than or equal to)
    • <= (less than or equal to)
  • Logical Operators: These operators combine boolean values.
    • && (logical AND): Returns true if both operands are true.
    • || (logical OR): Returns true if at least one operand is true.
    • ! (logical NOT): Reverses the boolean value (e.g., !true is false).
  • Assignment Operators:
    • = (assignment)
    • += (add and assign)
    • = (subtract and assign)
    • = (multiply and assign)
    • /= (divide and assign)
    • %= (remainder and assign)

Control Flow:

  • if Statements: Execute a block of code if a condition is true.

    if condition {
        // Code to execute if condition is true
    }
    
  • else if and else: Provide alternative blocks of code to execute.

    if condition1 {
        // Code if condition1 is true
    } else if condition2 {
        // Code if condition2 is true
    } else {
        // Code if no conditions are true
    }
    
  • loop: Creates an infinite loop. You typically use break to exit the loop.

    loop {
        // Code to repeat
        if condition {
            break; // Exit the loop
        }
    }
    
  • while: Repeats a block of code as long as a condition is true.

    while condition {
        // Code to repeat while condition is true
    }
    
  • for: Iterates over a sequence of values (e.g., a range, an array, a collection).

    for item in iterator {
        // Code to execute for each item
    }
    
  • break: Exits the innermost loop.

  • continue: Skips the rest of the current iteration and goes to the next iteration of the loop.

4. Live Coding Demonstration:

fn main() {
    // Arithmetic Operators
    let a = 10;
    let b = 3;
    let sum = a + b;
    let diff = a - b;
    let product = a * b;
    let quotient = a / b;
    let remainder = a % b;
    println!("Arithmetic: {} {} {} {} {}", sum, diff, product, quotient, remainder);

    // Comparison Operators
    let x = 5;
    let y = 7;
    let is_equal = x == y;
    let is_not_equal = x != y;
    let is_greater = x > y;
    println!("Comparison: {} {} {}", is_equal, is_not_equal, is_greater);

    // Logical Operators
    let p = true;
    let q = false;
    let and_result = p && q;
    let or_result = p || q;
    let not_result = !p;
    println!("Logical: {} {} {}", and_result, or_result, not_result);

    // Assignment Operators
    let mut z = 10;
    z += 5; // z = z + 5;
    println!("Assignment: {}", z);

    // if, else if, else
    let age = 18;
    if age >= 18 {
        println!("You are an adult.");
    } else if age >= 13 {
        println!("You are a teenager.");
    } else {
        println!("You are a child.");
    }

    // loop
    let mut counter = 0;
    loop {
        println!("Loop: {}", counter);
        counter += 1;
        if counter > 5 {
            break; // Exit the loop when counter is greater than 5
        }
    }

    // while
    let mut num = 5;
    while num > 0 {
        println!("While: {}", num);
        num -= 1;
    }

    // for loop (iterating over a range)
    for i in 0..5 { // 0..5 creates a range from 0 up to (but not including) 5
        println!("For: {}", i);
    }
     // for loop with continue
    for i in 0..5 {
        if i == 2 {
            continue; // Skip the rest of this iteration if i is 2
        }
        println!("For with continue: {}", i);
    }

    //Nested For
    for i in 0..3 {
        for j in 0..2{
            println!("{},{}",i,j);
        }
    }
}

5. Tasks

  1. Calculator: Write a program that takes two numbers and an operator (+, -, *, /) as input (you can hardcode the values in variables for now) and performs the corresponding operation. Print the result. Use an if/else if/else structure to select the operation.
  2. FizzBuzz: Write a program that prints the numbers from 1 to 100. But for multiples of 3, print “Fizz” instead of the number, and for multiples of 5, print “Buzz”. For numbers which are multiples of both 3 and 5, print “FizzBuzz”. Use a for loop and if/else if/else.
  3. Countdown: Write a program that uses a while loop to count down from 10 to 1, printing each number.
  4. Loop and Break: Use a loop to generate random numbers between 1 and 100 (you’ll need the rand crate for this – add rand = "0.8" to your Cargo.toml’s [dependencies] section, and use rand::Rng; at the top of your file). Exit the loop when a number greater than 90 is generated. Print the generated numbers.
use rand::Rng;

fn main() {
    let mut rng = rand::thread_rng();
    let random_number = rng.gen_range(1..=100); // Generates a number between 1 and 100 (inclusive)
    println!("Random Number: {}",random_number);
}
  1. Nested Loops: Create a program that uses nested for loops to print a multiplication table (up to 10x10). The output should look something like this:

    1 2 3 4 5 6 7 8 9 10
    2 4 6 8 10 12 14 16 18 20
    ...
    10 20 30 40 50 60 70 80 90 100
    
  2. Continue: Use a for loop to print number from 1 - 10 and when number equal 4 continue.