Hello,
This code print the even numbers from 1 to 10:
fn main() {
let mut x=[0;10];
let mut counter=0;
for number in 1..11 {
if (number%2) == 0 {
x[counter]=number;
println!("Number is: {}",x[counter]);
counter+=1;
}
}
}
If your goal is printing even numbers and only printing, I suppose the array ([0;10]) doesn't have a purpose. But if you need to store the even numbers and use them later, I think it's pretty good.
In rust we also like iterators so a different way of doing it will be:
let result = (1..)
.filter(|x| x%2 == 0) // We take even numebers
.inspect(|x| println!("Number is: {}", x)) // we print them
.take(10).collect::<Vec<i32>>(); // we collect into an array
Note that your use of take will take ten even integers, not just all integers from 1 to 10. This is a one-liner that only prints the even integers from 1 to 10:
(1..=10).filter(|x| x % 2 == 0).for_each(|x| println!("Number is: {x}"));
My take, less functional, more procedural, and trying to be as close as possible to the original post:
fn main() {
let mut x = Vec::with_capacity(10);
for number in 1..=10 {
if number % 2 == 0 {
x.push(number);
println!("Number is: {}", number);
}
}
println!("All numbers: {:?}", x);
println!("Total numbers selected: {}", x.len());
}