HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Print Consecutive numbers by comparing two parameters

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
comparingnumberstwoprintparametersconsecutive

Problem

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.

Solution

The function name is weird. What is it testing? A more appropriate name might be printInclusiveRange(…, …).

Since the bounds are inclusive, I would expect that for input 3,3, the output should be 3. Yet you output nothing.

I would also expect the output not to end with a Tab character.

Here's one solution that corrects those two problems, and also combines the loops:

public static void printInclusiveRange(int a, int b) {
    System.out.print(a);
    if (a != b) {
        int i = a;
        int step = (a < b) ? +1 : -1;
        do {
            i += step;
            System.out.print("\t" + i);
        } while (i != b);
    }
    System.out.println();  // Perhaps you want a newline here?
}

Code Snippets

public static void printInclusiveRange(int a, int b) {
    System.out.print(a);
    if (a != b) {
        int i = a;
        int step = (a < b) ? +1 : -1;
        do {
            i += step;
            System.out.print("\t" + i);
        } while (i != b);
    }
    System.out.println();  // Perhaps you want a newline here?
}

Context

StackExchange Code Review Q#90495, answer score: 12

Revisions (0)

No revisions yet.