I am creating a do-while-loop that prints start to end. The program checks different types of numbers to get, and whenever it's small to big number it checks out but not when it's big to small. Anyone interested to help a stupid student?
This is what my program looks like, my teacher told me " The fact that a do-always gonna do an iteration should mean that the task isn't possible to do with only a do-while, try adding something to your loop" but I can't seem to figure it out.
public static void runLoop(int start, int end) {
do {
System.out.print( start );
start ;
}
} while (start <= end );
}
CodePudding user response:
The problem with a do-while-loop is that it will always run the code at least once before checking the while-statement. So if the while-statement is already wrong at the beginning, the code will still run. If you want to use do-while instead of while, you should add something that prevents the code from running if the while-statement is already wrong at the beginning, like for example an if-statement.
if(start <= end)
{
do
{
System.out.print(start);
start ;
}
while(start <= end);
}
CodePudding user response:
Using "while" will prevent your code to be executed once even if "start" is greater than "end":
public static void runLoop(int start, int end) {
while(start <= end){
System.out.print( start );
start ;
}
} ;
}
CodePudding user response:
From what I understand you want to print out all the numbers between the start number and end number. This currently works when start is smaller than end because it only loops while start is less than or equal to end. If start is greater than end it will only print once.
Before you begin changing the start value, check if it is bigger than or smaller than the end value. This will let you know if you should increment ( ) or decrement (--) start. Then loop until start equals end.