I need to write a program that accepts a number from the user, divides that number by two until it reaches one or cannot be divided evenly anymore, then adds all of the quotients from each division and displays them.
So something like this should be displayed:
Please enter a number: 8
8/2=4
4/2=2
2/2=1
4+2+1= 7
I thought about using an array to possibly store the quotients but I just can't see how that would work.
Any help would be appreciated!
You need a variable to store the total. Use a loop to divide the input by 2 and add the new value of the total for as long as the input is an even number.
To check if a number is even you use the modulo operator, which returns the remainder in a division between integers. A number is even as long as n%2 != 1 (0 is not even).
How would I store the quotient after each division and still be able to divide the input by two multiple times?
If I do something like:
1 2 3 4
while (number%2!=1)
{
number=number/2;
}
that would work in dividing the number by two until it is no longer even
However, I would not be able to store the value of each quotient and still be able to divide said quotient by two again until it is no longer even.
Or do you know a way to do so?