Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

for loop backwards with if statement

I basically want to do something if whatever is true and if whatever is false I want to do the same thing but backwards. I tried it this way and it works but I’m wondering if there is a better way to do this. It would be nice to only write doSomething once. I also calculated 5000.799465 "by hand" which also doesn’t seem very nice. I appreciate any help, I’m using java.

if (whatever) {
    for (double j = 0.0001; j < 5001; j = j * 1.1) {
        doSomething(j);
    }
} else {
    for (double j = 5000.799465; j > 0.0001; j = j / 1.1) {
        doSomething(j);
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

It seems like whatever you are trying to do requires 187 iterations, so lets start there.

for(int i = 0; i < 187; i++){
  if(whatever)
    int j = .0001 * Math.pow(1.1, i);
  else
    int j = .0001 * Math.pow(1.1, 186 - i);

  doSomething();
}

The logic behind this is that you are going in opposite order if whatever is false by subtracting i from the exponent.

Now you can use j with your doSomething() but you won’t have to use wacky numbers for your loop, and you can easily change it if you must rework the code.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading