Deckard
Deckard

Reputation: 1433

Print Consecutive numbers by comparing two parameters

input 3,5 output should be 3,4,5

input 5,3 output should be 5,4,3

And the code

public static void test(int a, int b) {
        if(a>b) {
            for (int i = a; i >= b; i--) {
                System.out.print(i + "\t");
            }
        }else if(a<b) {
            for (int i = a; i <= b; i++) {
                System.out.print(i + "\t");
            }
        }
    }

It works but looks a little messy. Is it possible to do without if else thing? Only one loop.

Upvotes: 1

Views: 79

Answers (3)

SubOptimal
SubOptimal

Reputation: 22973

One solution which handle also boundary values correctly could be

public static void test(int start, int end) {
    int current = start;
    int stepWidth = current <= end ? +1 : -1;
    while (current != (end + stepWidth)) {
        System.out.print(current + "\t");
        current += stepWidth;
    }
    System.out.println("");
}

edit Another one using a for loop.

public static void test(int start, int end) {
    int stepWidth = start <= end ? 1 : -1;
    for (int current = start; current != end + stepWidth; current += stepWidth) {
        System.out.print(current + "\t");
    }
    System.out.println("");
}

executions

test(3, 5);
test(5, 3);
test(Integer.MAX_VALUE - 3, Integer.MAX_VALUE);
test(Integer.MIN_VALUE, Integer.MIN_VALUE + 3);

output

3   4   5   
5   4   3   
2147483644  2147483645  2147483646  2147483647  
-2147483648 -2147483647 -2147483646 -2147483645

Upvotes: 2

Tagir Valeev
Tagir Valeev

Reputation: 100199

How about this version?

public static void test(int a, int b) {
    int d = b > a ? 1 : -1; 
    for (int i = a; i != b; i+=d) {
        System.out.print(i + "\t");
    }
    System.out.println(b);
}

Upvotes: 1

Prashant
Prashant

Reputation: 4614

This my solution, feedback appreciated.

public static void test(int a, int b) {
            int middle = (a < b) ? (b - 1) : (a - 1);
            System.out.println(a + "," + middle + ","+b);
        }

Above will work only when a != b.

Upvotes: 0

Related Questions