Home > Software design >  for loop backwards with if statement
for loop backwards with if statement

Time:01-01

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

CodePudding user response:

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

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

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.

  • Related