Store results in a while loop

I am a complete beginner, I just need a hint or something to this problem:
We have to create a program where the user inputs a number, and figure out how many times the number can be divided by 2 until the remainder is 0. For example, if the input is 7, 7/2 = 3, 3/2 = 1,1/2=0, therefore, 7 can be divided by two for 3 times. The problem that I'm having is I don't know how to store the result so I use '3' instead of '7' when it loops. The end result basically says that '7 can be divided into 2 for 3 times.'

btw - it's a homework problem, so just a nudge in the right direction would be nice
Last edited on
You can modify the variable in the loop; another variable can be used to keep track of the count. If you want to use the input after the loop, you can 'save' it inside another variable that isn't used or modified inside the loop.
1/2 = 0.5, rounded up to 1.... so it never ends. Maybe consider using floats or doubles?

Anyway, my hint is this nifty piece of code
count+=1

Count is the variable that holds how many times its divided.

One more thing, I would suggest using a for loop instead of a while loop. But that's just me.
When performing operations on integers, the part after the '.' will be ignored: 1/2 will return 0. When considering the number as a 'normal' number, the number will never become 0, so I dont see how float or doubles will help.
You could use a for-loop, but IMO for-loops should be used when the number of times the loop will execute is known at the moment the program enters the loop, and so I think a while-loop is the best solution here.
According to the particular problem you point out in your question, you may need to look up variable scope. The first couple chapters of the Documentation on this site should have enough to solve your problem.
Last edited on
Let me reword the problem in a manner that should help make how to code it more clear.

You want to do some division on a number while it's greater than zero (integer division truncates, not rounds, so that's not an issue), and count the number of times you were able to divide.
Topic archived. No new replies allowed.