Divide User Input by 2 Until 1

Nov 10, 2014 at 7:01pm
Hii,,

I need to make a program that takes in a user’s number and keep dividing it by 2 until it is 1.I need to display the division steps

i'm kinda new to c++ and i do not know how to keep making it divide by 2 until 1

i tired this but it obviously did not work..

some help? :x

code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//Assignment 21 Program 4
#include <iostream>
using namespace std;

int main() {
    
//User Input

int input,total;

cout <<"Enter A Number To Be Divided By 2 Until 1" << endl << endl;
cout <<"Number: ";
cin >> input;
cout << "" <<endl;


do 

{
total=input/2;
cout <<input<<"/2= ";
cout <<total<<endl;
break;
} while (!input==1);

system ("pause");
return 0;
} 
Nov 10, 2014 at 7:57pm
The condition on line 24 is the same as: while ((!input) == 1) which will be false for any non-zero value of input. The break statement on line 23 makes the condition moot anyway. It always breaks out of the loop.


Also, there is no reason to have a variable named total.

Nov 10, 2014 at 10:07pm
I changed the do loop , but it only does it once , what do i need to do to change it to keep going until the total is 1.
Nov 10, 2014 at 10:47pm
You need to change the condition to: while(input != 1) or better while (input > 1)
Nov 10, 2014 at 11:55pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//Assignment 21 Program 4
#include <iostream>
using namespace std;
int main() {
//User Input
double input;
double total=0;
cout <<"Enter A Number To Be Divided By 2 Until 1" << endl << endl;
cout <<"Number: ";
cin >> input;
cout << "" <<endl;
do 
{
total=input/2;
break;
} while (input > 1);
cout <<input<<"/2: ";
cout <<total<<endl;
system ("pause");
return 0;
} 



I changed the condition but it still does it only once..
Nov 11, 2014 at 1:00am
Step through your code, LINE BY LINE try to understand what each statement does. What is your goal with this program? What is the program doing atm? If you still haven't seen the problem, look at line 15. Also total = input / 2 does not divide input by 2, it returns a number equivalent to input / 2. input = input / 2 will divide input by 2
Nov 11, 2014 at 1:29am
You have total = input / 2 and then loop while input > 1. So this will either a) loop forever or b) never loop.

Shouldn't you be assigning input to input / 2 (shift the bit right) and possibly do something with the divided value? Otherwise you might as well just set it equal to one.
Nov 11, 2014 at 7:37am
at line 15break; will be unconditionally executed, that will result in the ending of do...while loop.

and also at line 14 total = input / 2, input is not be changed, so is total , you should :
1.comment break;
2.assign input to total, before do...while structure
3.use total = total >> 1 to replace total = input/2
4. finally, loop continue condition is total > 1
Topic archived. No new replies allowed.