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:

//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;
}

} while (!input==1);

In C++, the not-equals logical test is !=, so try

} while (input!=1);

Anyway, you're testing the variable input. But you never change that variable. What is the variable total for? It's useless here. Remove it, and do your division operations on input.

You also need to get rid of line 23. that will force you out of the loop on the first iteration which is not what you want.

All 6 Replies

} while (!input==1);

In C++, the not-equals logical test is !=, so try

} while (input!=1);

Anyway, you're testing the variable input. But you never change that variable. What is the variable total for? It's useless here. Remove it, and do your division operations on input.

You also need to get rid of line 23. that will force you out of the loop on the first iteration which is not what you want.

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.

We're not psychic. Show us the loop and we'll tell you what the mistake is.

Heres the new code:

//Assignment 21 Program 4
#include <iostream>
using namespace std;
int main() {
//User Input
int input;
int total=0;
cout <<"Enter A Number To Be Divided By 2 Until 1" << endl << endl;
cout <<"Number: ";
cin >> input;
cout << "" <<endl;
do
{
cout <<input/2<<endl;
} while (input > 1);
system ("pause");
return 0;
}

You need to actually change input every loop. You can do that by using input /= 2; after line 17.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.