Solution 2: Return an Array of Squares
Solution:
fn arr_square() -> [i32;5] {
let mut square:[i32;5] = [1, 2, 3, 4, 5]; // mutable array
for i in 0..5 { // compute the square of each element
square[i] = square[i] * square[i];
}
square
}
fn main(){
println!("Updated Array : {:?}",arr_square());
}
output
Updated Array : [1, 4, 9, 16, 25]
- Explanation
- On line 2, a mutable array square of type i32 and size 5 is initialized with elements 1 , 2 , 3 , 4 ,5.
- On line 3, a for loop takes a variable i that iterates over the elements of the array square and squares each element and updates the square array on line 4.