In your code, you're not using i
at all. In fact, decNumber
is serving as the iteration index, because it's the thing that changes from one iteration of the loop to the next. You have lines in your code that perform the functions of all three parts of a for
loop -
- initialisation:
int decNumber = in.nextInt();
- continuation condition:
decNumber > 0
- increment:
decNumber = decNumber / 2
, which you can also write as decNumber /= 2
.
Note also that since you only use rem
inside the loop, it's better to declare it inside the loop, than right at the beginning.
Putting all this together, you can remain in the spirit of a for
loop, by rewriting your code as follows.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a decimal number: ");
for( int decNumber = in.nextInt(); decNumber > 0; decNumber /= 2 ) {
int rem = decNumber % 2;
System.out.println(rem);
}
}
This makes it clear how your loop is initialised, what the condition is that makes it continue, and what changes from one iteration to the next; so is better for readability than using a redundant index variable.