Print even numbers

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;
            }
    }
}

Is this code good?

Thank you.

Hi,

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
2 Likes

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}"));
4 Likes

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());
}

(Playground)


And here another variant, not close to the original:

fn main() {
    for x in (1..).map(|x| x * 2).take_while(|&x| x <= 10) {
        println!("{x}");
    }
}

(Playground)

2 Likes

I just stumbled upon the Iterator::step_by method:

fn main() {
    for x in (2..).step_by(2).take_while(|&x| x <= 10) {
        println!("{x}");
    }
}

(Playground)

The C equivalent would be:

int main() {
    for (int x=2; x<=10; x+=2) {
        printf("%i\n", x);
    }
    return 0;
}

I didn't know it could be written in Rust that way.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.