Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over every second number

Tags:

loops

rust

Reading the docs, I noticed a sentence saying: "Rust doesn't have a C style for loop.". So, I wonder, how can I make a loop equivalent to for(i = 0; i < 10; i += 2) { }?

The ways I can think of are something like:

for i in 0..10 {
    if i % 2 == 0 {
        //Do stuff
    }
}

Or even:

let i = 0;
loop {
    if i < 10 {
        //Do stuff
        i += 2;
    } else {
        break;
    }
}

But I'm not sure this is the best way, especially since it's really verbose. Is there a better way? I'm guessing it would be with iterators, but I'm not sure how I'd do that.

like image 728
someonewithpc Avatar asked Feb 23 '15 08:02

someonewithpc


People also ask

How to iterate through digits of a number in Java?

When divided by 10 print the remainder, and again divide the number by 10. Repeat it for each and every digit in the given number. The above program to iterate through digits of a number Java, traverse the digit in reverse order. For example if the number is 123456 then it traverse from right to left as 6, 5, 4, 3, 2, and 1.

How to iterate over a list in Python?

There are multiple ways to iterate over a list in Python. Let’s see all the different ways to iterate over a list in Python, and performance comparison between them. Method #1: Using For loop. Python3. list = [1, 3, 5, 7, 9] for i in list: print(i) Output: 1 3 5 7 9.

How do I loop over multiple iterables at the same time?

If you need to loop over multiple iterables at the same time, the best way to do that in Python is with the built-in zip function. Unlike, JavaScript, C, Java, and many other programming languages we don't have traditional C-style for loops.

How many ways can you iterate over a Dataframe?

Once you're familiar, let's look at the three main ways to iterate over DataFrame: Let's set up a DataFrame with some data of fictional people:


2 Answers

This is now implemented in std with the step_by function

for i in (0..10).step_by(2) {
    // Do stuff
}
like image 98
Hyp-X Avatar answered Sep 22 '22 13:09

Hyp-X


There's std::iter::range_step right now, but it's marked as unstable with the message "likely to be replaced by range notation and adapters".

fn main() {
    for i in std::iter::range_step(0, 10, 2) {
        println!("{:?}", i);
    }
}

prints

0
2
4
6
8
like image 31
Dogbert Avatar answered Sep 21 '22 13:09

Dogbert