Activity 8: Loops, Functions, and Variables
Your Names:
Part 1: What Does This Print?
Problem 1
#![allow(unused)] fn main() { let scores = [85, 92, 78]; for (i, score) in scores.iter().enumerate() { println!("Student {} scored {}", i, score); } }
Problem 2
#![allow(unused)] fn main() { let mut x = 0; for i in 1..=3 { x += i; } println!("{}", x); }
Problem 3
#![allow(unused)] fn main() { for i in (0..5).step_by(2) { if i == 2 { continue; } println!("{}", i); } }
Part 2: Quick Quiz
- Which is a correct function signature for a function
is_positivethat takes an integer and returns whether it's positive?
- What shell command lists all files in the current directory, including hidden files?
- What git command would you use to add all new and modified files to the staging area?
- What shell command would you use to move to your home directory?
Part 3: Fill-in-the-blanks
Problem 1
/// Returns the largest number in the array. fn find_max(numbers: [i32; 5]) -> _______ { let mut max = numbers[0]; for _______ in _______ { if _______ > max { max = _______; } } _______ } fn main() { let scores = [85, 92, 78, 96, 88]; let highest = find_max(_______); println!("Highest score: {}", highest); }
Problem 2
/// Counts the even numbers from 1 up to and including `limit`. fn count_even_numbers(limit: u32) -> u32 { let mut count = 0; for i in _______ { if i % 2 _______ { count _______; } } count } fn main() { let result = count_even_numbers(10); println!("Even numbers from 1 to 10: {}", _______); }
Problem 3
#![allow(unused)] fn main() { /// You start with a personal best of 100 and 3 lives. /// Each try uses up a life and raises your personal best by 25. /// Keep trying while your personal best is 210 or less and you still have lives. /// Then determine whether you got above 210, and then... can you look at the function signature and guess what you might return? fn try_to_set_a_high_score() -> u32 { let mut personal_best = 100; let mut lives_left = 3; _______ personal_best <= 210 _______ lives_left > 0 { personal_best _______ 25; // You get a little better every time! lives_left _______; println!("Score: {}, Lives left: {}", _______, _______); } _______ personal_best _______ { println!("High score achieved!"); } _______ { println!("Try again later"); } _______ } }
Part 4: Debug the Code
The line where you notice a bug is not always the line you change to fix it.
Problem 1 (3 bugs):
#![allow(unused)] fn main() { fn calculate_average(numbers: [f64]) -> f64 { // look here let mut sum = 0; for num in numbers { sum += num; // look here } sum / numbers.len() // look here } }
Bug 1: ________________________________________________
Fix 1: ________________________________________________
Bug 2: ________________________________________________
Fix 2: ________________________________________________
Bug 3: ________________________________________________
Fix 3: ________________________________________________
Problem 2:
#![allow(unused)] fn main() { let arr = [1, 2, 3]; for i in 0..arr.len() { arr[i] = arr[i] * 2; // look here } }
Bug: ________________________________________________
Fix: ________________________________________________
Problem 3 (2 bugs):
#![allow(unused)] fn main() { /// Find the first occurrence of an even number in the array. /// If there are no even numbers, return -1 instead fn find_first_even(numbers: [u32; 5]) -> u32 { for num in numbers { if num % 2 = 0 { // look here return num; } } return -1; // look here } }
Bug 1: ________________________________________________
Fix 1: ________________________________________________
Bug 2: ________________________________________________
Fix 2: ________________________________________________
Answers
Problem 1
Student 0 scored 85
Student 1 scored 92
Student 2 scored 78
The index starts at 0.
Problem 2
6
Problem 3
0
4
Part 2: Quick Quiz
fn is_positive(n: i32) -> boolls -aorls -lagit add .(orgit add -A)cd ~
Part 3: Fill-in-the-blanks
Problem 1
Two correct answers here. Looping over the values:
fn find_max(numbers: [i32; 5]) -> i32 { let mut max = numbers[0]; for num in numbers { if num > max { max = num; } } max } fn main() { let scores = [85, 92, 78, 96, 88]; let highest = find_max(scores); println!("Highest score: {}", highest); }
Or looping over the indices (0..5 works too):
#![allow(unused)] fn main() { fn find_max(numbers: [i32; 5]) -> i32 { let mut max = numbers[0]; for i in 0..numbers.len() { if numbers[i] > max { max = numbers[i]; } } max } }
Problem 2
fn count_even_numbers(limit: u32) -> u32 { let mut count = 0; for i in 1..=limit { if i % 2 == 0 { count += 1; } } count } fn main() { let result = count_even_numbers(10); println!("Even numbers from 1 to 10: {}", result); }
Prints Even numbers from 1 to 10: 5
Problem 3
#![allow(unused)] fn main() { fn try_to_set_a_high_score() -> u32 { let mut personal_best = 100; let mut lives_left = 3; while personal_best <= 210 && lives_left > 0 { personal_best += 25; // You get a little better every time! lives_left -= 1; println!("Score: {}, Lives left: {}", personal_best, lives_left); } if personal_best > 210 { println!("High score achieved!"); } else { println!("Try again later"); } personal_best } }
Three lives only gets to 175, so it prints "Try again later" and returns 175.
Part 4: Debug the Code
Problem 1
Bug 1: Array parameter needs a size
Fix 1: fn calculate_average(numbers: [f64; 5]) -> f64
Bug 2: sum starts as an integer but gets floats added to it
Fix 2: let mut sum = 0.0;
Bug 3: sum is a float but numbers.len() is an integer
Fix 3: sum / (numbers.len() as f64)
Problem 2
Bug: Array needs to be mutable to modify its elements
Fix: let mut arr = [1, 2, 3];
Problem 3
Bug 1: if num % 2 = 0
Fix 1: if num % 2 == 0
Bug 2: Cannot return -1 from a function that returns u32 (unsigned)
Fix 2: Change the return type to i32. Then return num needs return num as i32, because num is still a u32 (or you could make the input parameter an array of i32 as well)