Q:

Rust program to calculate the sum of array elements

belongs to collection: Rust Arrays Programs

0

In this program, we will create an integer array with 5 elements then we will calculate the sum of array elements.

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 calculate the sum of array elements is given below. The given program is compiled and executed successfully.

// Rust program to calculate the sum 
// of array elements

fn main() {
   let arr:[i32;5] = [1,2,3,4,5];
   let mut sum:i32 = 0;
   let mut i:usize = 0;
   
   while i<arr.len()
   {
	sum = sum + arr[i];	
	i = i + 1;
   }
   println!("Sum of array elements is: {}", sum);
}

Output:

Sum of array elements is: 15

Explanation:

Here, we created an array of the integer with 5 elements. Then we calculated the sum of array elements and stored the result into variable sum. After that, we printed the result.

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 find the largest element from the ... >>
<< Rust program to create an array using the existing...