273,112 views
1 vote
1 vote
Write a java program that prints the following sequences (in the given order) using a while loop. The numbers in the sequences can be printed on a single line or on separate lines.

a) 2, 3, 4, ... , 14, 15
b) -10, -9, -8, ... , 9, 10
c) 100, 99, 98 ... , 91, 90
d) 40, 37, 34, ... , 25, 22

User Nathan Werth
by
2.5k points

1 Answer

23 votes
23 votes

Answer:

class Main {

static void sequence(int n, int end, int step) {

for(;step>0 ? n<=end : n>=end; n += step) {

System.out.printf("%d",n);

if (n != end) System.out.printf(", ");

}

System.out.println();

}

public static void main(String[] args) {

sequence(2, 15, 1);

sequence(-10, 10, 1);

sequence(100, 90, -1);

sequence(40, 22, -3);

}

}

Step-by-step explanation:

Here is my solution again after being removed previously.

User Adedotun
by
3.2k points