Rust Program: Calculate product of Tuple elements
Rust Iterators and Iterator Adapters: Exercise-4 with Solution
Write a Rust program that iterates over a vector of tuples (i32, i32) and calculates the product of the first and second elements of each tuple.
Sample Solution:
Rust Code:
fn main() {
// Define a vector of tuples
let tuples = vec![(10, 20), (30, 40), (50, 60)];
// Iterate over each tuple in the vector
for &(x, y) in tuples.iter() {
// Calculate the product of the first and second elements of the tuple
let product = x * y;
// Print the product
println!("Product of ({}, {}) is {}", x, y, product);
}
}
Output:
Product of (10, 20) is 200 Product of (30, 40) is 1200 Product of (50, 60) is 3000
Explanation:
In the exercise above,
- Define a vector 'tuples' containing a list of tuples (i32, i32).
- We use a "for" loop with tuple pattern matching to iterate over each tuple in the vector.
- For each tuple (x, y), we calculate the product x * y and print it along with the original tuple elements.
Rust Code Editor:
Previous: Rust Program: Print length of strings.
Next: Rust Program: Count True and False values.
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://w3resource.com/rust/functional-programming/rust-iteretors-and-iterator-adapters-exercise-4.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics