15,030,183 members
See more:
Right now my code is able to print out all the numbers between the two int:s "start" and "end". My problem is that the code only works if the variabel start < end and not the other way around. If start > end, then it just loops 2 digits over and over again.

Example: if start = 3 and end = 6 and i run the program, then it will print out "3456"

But if start = 5 and end = 2 and i run the program, then it will print out "545454545454545454545..."

Any guidance would be greatly appreciated!

What I have tried:

public static void runLoop(int start, int end){

while(start != end +1){
if (start > end){
System.out.print(start);
start--;
}
System.out.print(start);
start++;

}
}
Posted
Updated 16-Jun-21 8:34am
Gerry Schmitz 16-Jun-21 14:36pm

You can probably get your head around it if you create 2 loops: one for start < end; another for start > end. You also have to consider when start == end.

## Solution 1

Try this

Java
```public static void runLoop(int start, int end)
{
if (start < end)
{
while(start <= end)
{
System.out.print(start);
start++;
}
}
else
{
while(start >= end)
{
System.out.print(start);
start--;
}
}
}```
v2
Maciej Los 16-Jun-21 15:27pm

:) 5ed!

## Solution 2

Your current code compares the values each time round the loop, so if start is greater than end you print it, reduce the value ... and then print it again, and put it back where it was ...

There are several ways you can do this:
1) Compare start and end before the loop and then have two loops: one where start is greater than end and which runs "down"; one where start is less than end which runs "up".
2) Compare start and end before the loop and set a "direction" variable to 1 or -1. Then make your loop run while start and end are different and change start by "direction" after you print it.