Heroge Heroge - 1 month ago 7
Java Question

Java For-Loop Number Series

I'm trying to print a number series that divides by 2 which would result in an output of 128, 64, 32, 16, 8, 4, 2, 1

int num = 128;
for (int i = 1; i <= 8; i++)
{
int prevNum = 0;
prevNum = num / 2;

System.out.print(prevNum);
System.out.print(", ");
}


Clearly my current code isn't working as it is only outputting the number 64 eight times. I'm not sure how I can throw away the initial number after printing it and only use the stored number after the division

Answer

From the code that you have posted, I feel that you have initialised num as 128 somewhere in your code.

Now in your loop you are storing prevNum as num/2 in other words 128/2 each time in the loop. So you are getting 64 as output 8 times as your loop loops 8 times.

The correction I would suggest in this code is you do not require the second variable prevNum. Simply use num = num/2 and print the value of num variable. This will solve your problem.

A better code for this loop would be :

int num = 128;
while (num > 1) // This takes care of the loop. 
                //Also if you write num = 256, then also this loop would work.
{
    num = num / 2;

    System.out.print(num);
    System.out.print(", ");         
}