java - Print Consecutive numbers by comparing two parameters -


input 3,5 output should 3,4,5

input 5,3 output should 5,4,3

and code

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

it works looks little messy. possible without if else thing? 1 loop.

one solution handle boundary values correctly 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 1 using loop.

public static void test(int start, int end) {     int stepwidth = start <= end ? 1 : -1;     (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 

Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -