Q:

Rust program to pass an array into the function using call by value mechanism

belongs to collection: Rust Arrays Programs

0

In this program, we will create an integer array with 5 values. Then we will pass created array into a user-defined function using the call by value mechanism.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to pass an array into a function using the call by value mechanism is given below. The given program is compiled and executed successfully.

// Rust program to pass an array into function 
// using the call by value mechanism

fn ModifyArray(mut intArr:[i32;5]){
   for i in 0..5 {
      intArr[i] = 10;
   }
   println!("Array elements inside ModifyArray() function:\n{:?}",intArr);
}

fn main() {
   let intArr:[i32;5] = [1,2,3,4,5];
   
   ModifyArray(intArr);

   println!("Array elements inside main() function:\n{:?}",intArr);
}

Output:

Array elements inside ModifyArray() function:
[10, 10, 10, 10, 10]
Array elements inside main() function:
[1, 2, 3, 4, 5]

Explanation:

In the above program, we created two functions ModifyArray() and main(). The ModifyArray() is a user-defined function, it accepts an array as a call by value. Here we modified the elements of the array but modification will not reflect in the calling function.

In the main() function, we created an array intArr with 5 integer values. Then we passed created array in the ModifyArray() function and then printed the array elements.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Rust Arrays Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Rust program to pass an array into the function us... >>
<< Rust program to access array elements using iter()...