Killerpixler
Killerpixler

Reputation: 4050

only execute a statement every millionth time in a loop

I have a while loop that runs around 10 million times incrementing a variable "day" every time. I want the program to only print a line when a million days has passed (i.e.

1 million days have passed

2 million days have passed

...

Loop is done

so far I have the code:

double dayMill; //outside the loop
...
dayMill = day/1000000; //every runthrough of the loop

I was thinking about using an if statement with with things like

if( (int)dayMill == dayMill){}

because when day = 1,000,000 then daymill = 1 so cast as an int it is 1 as well. However this doesn't work. It prints 0.0 million days... a lot until 1.0 a lot..... never just the one line for each million i want

Upvotes: 0

Views: 143

Answers (6)

OscarRyz
OscarRyz

Reputation: 199254

What I would do is:

int count = 0;
int times = 1_000_000;
while (true) {
    ....
    if ( ++count % times == 0 ) {
       ...
    }
}

Upvotes: 0

Cliff Ribaudo
Cliff Ribaudo

Reputation: 9039

Or....

i++;
if(i == 1000000) {
    print stuff;
    i=0;
}

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533640

You can use modulus

for (long i = 1; ; i++) {
    if (i % 1000000 == 0)
        System.out.println(i);

}

prints

1000000
2000000
3000000
4000000
5000000
6000000
7000000
... etc ...

Upvotes: 0

John
John

Reputation: 16007

Whatever your loop index is,

if (index % 1000000 == 0)
{
    // do your magic
}

Upvotes: 1

koljaTM
koljaTM

Reputation: 10262

How about

if (day % 1000000 == 0) {...}

Upvotes: 1

thatidiotguy
thatidiotguy

Reputation: 9011

if(dayMill % 1000000 == 0)
{
    //print statement
}

That is if you make dayMill an int. Why is it a double if you are incrementing by one? I guess I do not really understand what you are doing exactly.

Upvotes: 6

Related Questions