Activity 13 - Midterm 1 Practice Problems


Name:


Practice Problem Set A

You will have 10 minutes to complete these problems

Problem A1: Fill in the Blanks

Complete this function that finds the largest and smallest numbers in an array:

fn find_min_and_max(numbers: [i32; 5]) -> __________ {

    let mut min = _______________ ;

    let mut max = _______________ ;

    for num _____________ {

        if num ____________ min {

            min = ____________;

        }

        if num ____________ max {

            max = ____________;
        }
    }
    _______________
}

fn main() {
    let scores = [85, 92, 78, 96, 88];
    let result = find_min_and_max(scores);
    println!("Min: {}, Max: {}", ______________);
}

Problem A2: Debug the Code

This code has 3 bugs. Find and fix them:

#![allow(unused)]
fn main() {
fn calculate_grade(points: f32, total: f32) -> Result<char, String> {
    if total = 0.0 {
        return Err("Total cannot be zero".to_string());
    }

    let percentage = (points / total) * 100;

    match percentage {
        x if x >= 90.0 => Ok('A'), // hint - there's nothing wrong with the 
        x if x >= 80.0 => Ok('B'), // `x if x >= 90.0 ` notation here
        x if x >= 70.0 => Ok('C'),
        x if x >= 60.0 => Ok('D'),
        x if x >= 0.0 => Ok('F'),
    }
}
}
  1. _____________ should be _____________ because _____________

  2. _____________ should be _____________ because _____________

  3. _____________ should be _____________ because _____________

Problem A3: Find the Bug

This code has 2 bugs. Find and fix them:

#![allow(unused)]
fn main() {
fn sum_integers_if_positive(nums: [i32; 3]) -> Option<i32> {
    let mut total = 0;
    for num in nums.iter().enumerate() {
        if num < 0 {
            return None;
        }
        total += num;
    }
    Ok(total)
}
}
  1. _____________ should be _____________ because _____________

  2. _____________ should be _____________ because _____________




Practice Problem Set B: Hand-Coding Problem

Write a function that validates if numbers are in a valid range using an enum.

Then write a function that uses that function to find the average of valid numbers in an array

#[derive(Debug)]
enum ValidationResult {
    Valid,
    TooSmall,
    TooBig,
}

// Complete this function:
fn validate_number(num: i32, min: i32, max: i32) -> ValidationResult {
    // Your code here - return appropriate ValidationResult variant








}

fn average_of_valid_numbers(arr: [i32 ; 5], min: i32, max: i32) -> Option<f32> {
    // Use validate_number to find which numbers are valid in the array
    // and return their average
    // If there are no valid numbers, return None rather than a value.
















}

fn main() {
    let small_type = validate_number(1, 2, 3);
    let avg = average_of_valid_numbers([1,5,3,2,5], 2, 4);
    println!("{:?}", small_type); // this should print TooSmall
    println!("{:?}", avg); // this should print Some(2.5)
}