Rust Program: Calculate sum of range of numbers
Rust Iterators and Iterator Adapters: Exercise-2 with Solution
Write a Rust program that iterates over a range of numbers and calculates the sum of all numbers.
Sample Solution:
Rust Code:
fn main() {
// Define the start and end values for the range
let start = 1;
let end = 10;
// Calculate the sum of numbers in the range using the sum() method
let sum: i32 = (start..=end).sum();
// Print the sum of numbers from start to end
println!("Sum of numbers from {} to {} is: {}", start, end, sum);
}
Output:
Sum of numbers from 1 to 10 is: 55
Explanation:
In the exercise above,
- Define the start and end values of the range (inclusive).
- Use the "sum()" method on the range to calculate the sum of all numbers within the range.
- Finally the result is printed to the console.
Rust Code Editor:
Previous: Rust Program: Iterate over vector of integers.
Next: Rust Program: Print length of strings.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/rust/functional-programming/rust-iteretors-and-iterator-adapters-exercise-2.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics