Rasmus
Rasmus

Reputation: 241

Two if statements - one isn't working

I have a problem with printing even numbers. If i put the arguments as 1,7 it prints out the even numbers in between (2,4,6) which is exactly what I intend. When int i is greater than int n, I want it to print out in a decreasing manner, but the if statement isn't executing at all. I can't figure out what the problem is???

public class Problem {

public static void main(String[] args) {
  printEven(1,7);
  printEven(21, 15);
//main
}

  public static void printEven(int i, int n) {

  System.out.print("[ ");
  //if n is greater than i
  if (i <= n) {
     for (int t = i; t <= n; t++) {
        if (t % 2 == 0) {
           System.out.print(t + " ");
        //if statement inner
        }
     //for loop
     }
  //if statement outer
  }
  //if i is greater than n
  if (i >= n) {
     for (int t = n; t >= i; t--) {
        if (t % 2 == 0) {
           System.out.print(t + " ");
        //if statement inner
        }
     //for loop
     }
  //if statement outer
  }
  System.out.print("]");
  System.out.println();  
//printEven
}

//class
}

Upvotes: 0

Views: 86

Answers (3)

sukhmel
sukhmel

Reputation: 1482

In addition to what others already pointed out, I would recommend to write something like

int begin = (i < n)? i:  n;
int   end = (i < n)? n:  i;
int  step = (i < n)? 1: -1;
for (int t = begin; step*t < step*end + 1; t += step)
{ 
    /*...*/
}

instead of having two for-loops, so that you will not have to change your code twice when doing changes. This will be handy if you have complicated logic inside of loop.

Upvotes: 1

DevGoldm
DevGoldm

Reputation: 828

Change: for (int t = n; t >= i; t--)

to: for (int t = i; t >= n; t--)

Upvotes: 0

Andromeda
Andromeda

Reputation: 1368

The problem is in the line

for (int t = n; t >= i; t--) {  

change it to:

   for (int t = i; t >= n; t--) {    //this is how it should be   

So, your code should look like.

if (i >= n) {
     //for (int t = n; t >= i; t--) {  // **this is wrong code.**
       for (int t = i; t >= n; t--) {    //this is how it should be
        if (t % 2 == 0) {
           System.out.print(t + " ");
        //if statement inner
        }
     //for loop
     }
  //if statement outer
  }

Upvotes: 0

Related Questions