Rust Program: Count True and False values
Rust Iterators and Iterator Adapters: Exercise-5 with Solution
Write a Rust program that iterates over a vector of booleans and counts the number of false and true values.
Sample Solution:
Rust Code:
fn main() {
// Define a vector of boolean values
let booleans = vec![true, false, true, true, false, false, true, true, false];
// Initialize counters for true and false values
let (mut true_count, mut false_count) = (0, 0);
// Iterate over each boolean value in the vector
for &value in booleans.iter() {
// Increment the respective counter based on the boolean value
if value {
true_count += 1;
} else {
false_count += 1;
}
}
// Print the counts of true and false values
println!("Number of true values: {}", true_count);
println!("Number of false values: {}", false_count);
}
Output:
Number of true values: 5 Number of false values: 4
Explanation:
In the exercise above,
- We define a vector 'booleans' containing a list of boolean values.
- We initialize two variables 'true_count' and 'false_count' to keep track of the counts of true and false values, respectively.
- We use a "for" loop to iterate over each 'boolean' value in the vector.
- Inside the loop, we check each value. If it's 'true', we increment 'true_count'; if it's 'false', we increment 'false_count'.
- After the loop, we print the counts of true and false values.
Rust Code Editor:
Previous: Rust Program: Calculate product of Tuple elements.
Next: Rust Program: Calculate average of Float 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://www.w3resource.com/rust/functional-programming/rust-iteretors-and-iterator-adapters-exercise-5.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics