decimal to binary converter c++? - c++

int inputNumber=0;
int divisionStore=0,modStore=0;
vector<int> mainVector;
cout << "\nEnter a Number to Convert to Binary.\n" << endl;
cin >> inputNumber;
do
{
modStore=inputNumber%2;
inputNumber=inputNumber/2;
mainVector.push_back(modStore);
}while(inputNumber!=1);
for (int i=0;i<mainVector.size();i++)
{
cout<<endl<<mainVector[i]<<endl;
}
Seems like there is a logical error but I cant find whats wrong with it? The program does not print the correct conversion as it seems like the loop ends before it can push the last number.

I think you need to change:
}while(inputNumber!=1)
to:
}while(inputNumber!=0)

Why not use the STL - i.e. bitset
See http://www.cplusplus.com/reference/bitset/bitset/to_string/
Probably do it in a couple lines of code!

Seams to be a very complicated and inefficient way (if I don't misunderstand you). You are probably looking for bit-manipulation operators, not /, % etc. If you really want to stick it in a vector this should do it:
while (inputNumber) {
mainVector.push_back(inputNumber & 1);
inputNumber >>= 1;
}
Note however that this will put the least significant bit at the beginning of the vector, may not be what you want but looks like it is what your code is trying to do as well.

I answered similar question Here, I used recursion function
void decimal_to_binary(int decimal)
{
int remainder = decimal % 2;
if (decimal < 1)
return;
decimal_to_binary(decimal / 2);
cout << remainder;
}

inputNumber%2 is the least significant bit, so your vector will contain the bits in reversed order. Simply loop the vector in reversed order.
while(inputNumber!=1) - You have to loop while inputNumber!=0, otherwise you won't process the last bit.

#include<iostream>
using namespace std;
int main(){
int x,bin;
x=0 ,bin=0;
int ar[10000];
cout<<"Enter Decimal Number "<<endl;
cin>>x;
int n=0;
while(x>0){
bin=x%2;
x=x/2;
ar[n]=bin;
n++;
}
cout<<endl;
n=n-1;
for(n;n>=0;n--){
cout<<ar[n]; }
cout<<endl;
return 0;
}
/* Try this */

Related

How to split a number into digits in C++ [duplicate]

This question already has answers here:
Converting integer into array of digits [closed]
(4 answers)
Closed 2 years ago.
I know there are similar questions on Stack overflow about this. I already checked them. Here are two points:
The number will be an input from the user, so I won't know how many digits the number may actually contain
I DON'T want to directly print the digits, I need to do some further process on every digit, so I need a way to save or assign every single digit.
So fore example, if the user enters 1027, I'll need 1, 0, 2, 7 returned, and not printed. That's where my problem starts.
Here's how I'd write it if it could be printed:
int x;
cin>>x;
while(x != 0)
{
cout<<x%10<<endl;
x/=10;
}
Any hints or help is in advance appreciated.
It depends what order you need it in. If you need least-significant digit (rightmost) to most-significant (leftmost), then your solution is almost there
int x = ...
while(x != 0)
{
int current = x % 10; // get rightmost digit
x /= 10;
// process 'current', or store in a container for later processing
}
If you need most-significant (leftmost) to least-significant (rightmost), then you can do this recursively:
void for_each_digit(int input)
{
// recursive base case
if (input == 0) { return; };
int current = input % 10
for_each_digit(input / 10); // recurse *first*, then process
// process 'current', add to container, etc
}
// ...
int x = ...
for_each_digit(x);
Edit: I apparently missed the part about returning a sequence of digits.
Either approach works. If you go right-to-left, you will need to reverse the container first. If you go recursive, you will need to append each value to the container.
Use a std::string:
std::string input;
std::cin >> input;
Now input[i] is the i-th digit. input.size() is the number of digits.
Well you can use vector. It can take variable length input. You need not declare the size beforehand. Learn more about vector here: vector
#include<iostream>
#include<vector>
#include <algorithm> // std::reverse
using namespace std;
int main(void)
{
vector<int>digits;
int x;
cin >> x;
while(x)
{
digits.push_back(x % 10);
x = x / 10;
}
// reversing the order of the elements inside vector "digits" as they are collected from last to first and we want them from first to last.
reverse(digits.begin(), digits.end());
// Now the vector "digits" contains the digits of the given number. You can access the elements of a vector using their indices in the same way you access the elements of an array.
for(int i = 0; i < digits.size(); i++) cout << digits[i] << " ";
return 0;
}
You may try std::vector<int> to store unknown number of integers as shown:
#include <iostream>
#include <vector>
int main(void) {
std::vector<int> digits;
std::string s;
std::cout << "Enter the number: ";
std::cin >> s;
size_t len = s.length();
for (size_t i = 0; i < len; i++) {
digits.push_back(s[i] - '0');
}
// Comment next 3 code to stop getting output
for (size_t i = 0; i < len; i++)
std::cout << digits[i] << ' ';
std::cout << std::endl;
return 0;
}
Note: This approach doesn't performs any mathematical operations (i.e. operation of division and getting remainders). It simply stores each integer in a vector using a for loop.

Illegal use of floating point in c++

I am getting an illegal use of floating point error in my programme:
#include<iostream.h>
#include<conio.h>
#include<math.h>
void main()
{
clrscr();
int number,reverse,check,i,j,k=0,x;
cout<<"Please enter number: ";
cin>>number;
//Obtaining no. of digits:
for(i=1;check==0;i++)
{
check/=10;
}
//Reversing number:
if(i%2==0) //case even digits
{ for(j=i;j>0;j--)
{
x=(number%pow(10,j))/pow(10,j-1); //here
reverse+=x*pow(10,k);
k++;
}
}
cout<<"Reverse number: "<<reverse;
getch();
}
I have no idea why this error is appearing, it would be great if someone could help me with this
pow is a function that returns a double. and the C++ modulo operator % works only with integer numbers. That's because the mathematical modulo operator is defined for integers. Hence the illegal use.
Besides, you use the check variable without initialization. Initialize all you variables before use, in order to avoid further surprises.
EDIT
Here are some other corrections to do:
check = number before the first for loop.
for(i = 0; check != 0; i++)
Finally, try to find another way to get the digits of the number, without using pow. There are simple ways using consecutive integer division.

Need advice on improving my code: Search Algorithm

I'm pretty new at C++ and would need some advice on this.
Here I have a code that I wrote to measure the number of times an arbitrary integer x occurs in an array and to output the comparisons made.
However I've read that by using multi-way branching("Divide and conqurer!") techniques, I could make the algorithm run faster.
Could anyone point me in the right direction how should I go about doing it?
Here is my working code for the other method I did:
#include <iostream>
#include <cstdlib>
#include <vector>
using namespace std;
vector <int> integers;
int function(int vectorsize, int count);
int x;
double input;
int main()
{
cout<<"Enter 20 integers"<<endl;
cout<<"Type 0.5 to end"<<endl;
while(true)
{
cin>>input;
if (input == 0.5)
break;
integers.push_back(input);
}
cout<<"Enter the integer x"<<endl;
cin>>x;
function((integers.size()-1),0);
system("pause");
}
int function(int vectorsize, int count)
{
if(vectorsize<0) //termination condition
{
cout<<"The number of times"<< x <<"appears is "<<count<<endl;
return 0;
}
if (integers[vectorsize] > x)
{
cout<< integers[vectorsize] << " > " << x <<endl;
}
if (integers[vectorsize] < x)
{
cout<< integers[vectorsize] << " < " << x <<endl;
}
if (integers[vectorsize] == x)
{
cout<< integers[vectorsize] << " = " << x <<endl;
count = count+1;
}
return (function(vectorsize-1,count));
}
Thanks!
If the array is unsorted, just use a single loop to compare each element to x. Unless there's something you're forgetting to tell us, I don't see any need for anything more complicated.
If the array is sorted, there are algorithms (e.g. binary search) that would have better asymptotic complexity. However, for a 20-element array a simple linear search should still be the preferred strategy.
If your array is a sorted one you can use a divide to conquer strategy:
Efficient way to count occurrences of a key in a sorted array
A divide and conquer algorithm is only beneficial if you can either eliminate some work with it, or if you can parallelize the divided work parts accross several computation units. In your case, the first option is possible with an already sorted dataset, other answers may have addressed the problem.
For the second solution, the algorithm name is map reduce, which split the dataset in several subsets, distribute the subsets to as many threads or processes, and gather the results to "compile" them (the term is actually "reduce") in a meaningful result. In your setting, it means that each thread will scan its own slice of the array to count the items, and return its result to the "reduce" thread, which will add them up to return the final result. This solution is only interesting for large datasets though.
There are questions dealing with mapreduce and c++ on SO, but I'll try to give you a sample implementation here:
#include <utility>
#include <thread>
#include <boost/barrier>
constexpr int MAP_COUNT = 4;
int mresults[MAP_COUNT];
boost::barrier endmap(MAP_COUNT + 1);
void mfunction(int start, int end, int rank ){
int count = 0;
for (int i= start; i < end; i++)
if ( integers[i] == x) count++;
mresult[rank] = count;
endmap.wait();
}
int rfunction(){
int count = 0;
for (int i : mresults) {
count += i;
}
return count;
}
int mapreduce(){
vector<thread &> mthreads;
int range = integers.size() / MAP_COUNT;
for (int i = 0; i < MAP_COUNT; i++ )
mthreads.push_back(thread(bind(mfunction, i * range, (i+1) * range, i)));
endmap.wait();
return rfunction();
}
Once the integers vector has been populated, you call the mapreduce function defined above, which should return the expected result. As you can see, the implementation is very specialized:
the map and reduce functions are specific to your problem,
the number of threads used for map is static,
I followed your style and used global variables,
for convenience, I used a boost::barrier for synchronization
However this should give you an idea of the algorithm, and how you could apply it to similar problems.
caveat: code untested.

Get the maximum number from an integer array in C++

I have another task for my school and it is:
Write a program which will output the largest from three inputed numbers
So far I have done this:
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int* numbers = new int[3];
for(int i = 0; i < 3; i++) {
cout << "Input number no. " << (i + 1);
cin >> numbers[i];
cout << endl;
}
system("PAUSE");
return EXIT_SUCCESS;
}
Is there a helper function/method in C++ which will find a largest number in my numbers array?
There's an algorithm that finds the maximal element in a container (std::max_element), but that's inappropriate. Your situation can be solved with constant memory consumption, so you don't need to store all numbers. At any given point, you just need to remember the current maximum.
Imagine you had to process one gazillion numbers. Then storing them all would not be desirable.
Of course, internally the max_element algorithm does the same as I just suggested, but it assumes that you already have the container anyway. If you don't, then just update the maximum on the fly. The boost.accumulators library has something to do that, but I'm sure you can write this yourself — it should only take one or two lines.
In the following code snippet, max will contain the highest number from the list:
int i;
int max=numbers[0];
for(i=1;i<3;i++)
{
if(numbers[i]>max) max=numbers[i];
}
Note: Your array looks too small - it has a size of two and I'm pretty sure you want a size of three.
You don't need an array here. Just look at the numbers as they come in:
int largest = std::numeric_limits<int>::min();
for (int i = 0; i < 3; ++i) {
int value;
std::cin >> value;
if (largest < value)
largest = value;
}

Prime numbers program

I'm currently trying out some questions just to practice my programming skills. ( Not taking it in school or anything yet, self taught ) I came across this problem which required me to read in a number from a given txt file. This number would be N. Now I'm suppose to find the Nth prime number for N <= 10 000. After I find it, I'm suppose to print it out to another txt file. Now for most parts of the question I'm able to understand and devise a method to get N. The problem is that I'm using an array to save previously found prime numbers so as to use them to check against future numbers. Even when my array was size 100, as long as the input integer was roughly < 15, the program crashes.
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
int main() {
ifstream trial;
trial.open("C:\\Users\\User\\Documents\\trial.txt");
int prime;
trial >> prime;
ofstream write;
write.open("C:\\Users\\User\\Documents\\answer.txt");
int num[100], b, c, e;
bool check;
b = 0;
switch (prime) {
case 1:
{
write << 2 << endl;
break;
}
case 2:
{
write << 3 << endl;
break;
}
case 3:
{
write << 5 << endl;
break;
}
case 4:
{
write << 7 << endl;
break;
}
default:
{
for (int a = 10; a <= 1000000; a++) {
check = false;
if (((a % 2) != 0) && ((a % 3) != 0) && ((a % 5) != 0) && ((a % 7) != 0)) // first filter
{
for (int d = 0; d <= b; d++) {
c = num[d];
if ((a % c) == 0) {
check = true; // second filter based on previous recorded primes in array
break;
}
}
if (!check) {
e = a;
if (b <= 100) {
num[b] = a;
}
b = b + 1;
}
}
if ((b) == (prime - 4)) {
write << e << endl;
break;
}
}
}
}
trial.close();
write.close();
return 0;
}
I did this entirely base on my dummies guide and myself so do forgive some code inefficiency and general newbie-ness of my algorithm.
Also for up to 15 it displays the prime numbers correctly.
Could anyone tell me how I should go about improving this current code? I'm thinking of using a txt file in place of the array. Is that possible? Any help is appreciated.
Since your question is about programming rather than math, I will try to keep my answer that way too.
The first glance of your code makes me wonder what on earth you are doing here... If you read the answers, you will realize that some of them didn't bother to understand your code, and some just dump your code to a debugger and see what's going on. Is it that we are that impatient? Or is it simply that your code is too difficult to understand for a relatively easy problem?
To improve your code, try ask yourself some questions:
What are a, b, c, etc? Wouldn't it better to give more meaningful names?
What exactly is your algorithm? Can you write down a clearly written paragraph in English about what you are doing (in an exact way)? Can you modify the paragraph into a series of steps that you can mentally carry out on any input and can be sure that it is correct?
Are all steps necessary? Can we combine or even eliminate some of them?
What are the steps that are easy to express in English but require, say, more than 10 lines in C/C++?
Does your list of steps have any structures? Loops? Big (probably repeated) chunks that can be put as a single step with sub-steps?
After you have going through the questions, you will probably have a clearly laid out pseudo-code that solves the problem, which is easy to explain and understand. After that you can implement your pseudo-code in C/C++, or, in fact, any general purpose language.
There are a two approaches to testing for primality you might want to consider:
The problem domain is small enough that just looping over the numbers until you find the Nth prime would probably be an acceptable solution and take less than a few milliseconds to complete. There are a number of simple optimizations you can make to this approach for example you only need to test to see if it's divisible by 2 once and then you only have to check against the odd numbers and you only have to check numbers less than or equal to the aquare root of the number being tested.
The Sieve of Eratosthenes is very effective and easy to implement and incredibly light on the math end of things.
As for why you code is crashing I suspect changing the line that reads
for( int d=0; d<=b; d++)
to
for( int d=0; d<b; d++)
will fix the problem because you are trying to read from a potentially uninitialized element of the array which probably contains garbage.
I haven't looked at your code, but your array must be large enough to contain all the values you will store in it. 100 certainly isn't going to be enough for most input for this problem.
E.g. this code..
int someArray[100];
someArray[150] = 10;
Writes to a location large than the array (150 > 100). This is known as a memory overwrite. Depending on what happened to be at that memory location your program may crash immediately, later, or never at all.
A good practice when using arrays is to assert in someway that the element you are writing to is within the bounds of the array. Or use an array-type class that performs this checking.
For your problem the easiest approach would be to use the STL vector class. While you must add elements (vector::push_back()) you can later access elements using the array operator []. Vector will also give you the best iterative performance.
Here's some sample code of adding the numbers 0-100 to a vector and then printing them. Note in the second loop we use the count of items stored in the vector.
#include <vector> // std::vector
...
const int MAX_ITEMS = 100;
std::vector<int> intVector;
intVector.reserve(MAX_ITEMS); // allocates all memory up-front
// add items
for (int i = 0; i < MAX_ITEMS; i++)
{
intVector.push_back(i); // this is how you add a value to a vector;
}
// print them
for (int i = 0; i < intVector.size(); i++)
{
int elem = intVector[i]; // this access the item at index 'i'
printf("element %d is %d\n", i, elem);
}
I'm trying to improve my functional programming at the moment so I just coded up the sieve quickly. I figure I'll post it here. If you're still learning, you might find it interesting, too.
#include <iostream>
#include <list>
#include <math.h>
#include <functional>
#include <algorithm>
using namespace std;
class is_multiple : public binary_function<int, int, bool>
{
public:
bool operator()(int value, int test) const
{
if(value == test) // do not remove the first value
return false;
else
return (value % test) == 0;
}
};
int main()
{
list<int> numbersToTest;
int input = 500;
// add all numbers to list
for(int x = 1; x < input; x++)
numbersToTest.push_back(x);
// starting at 2 go through the list and remove all multiples until you reach the squareroot
// of the last element in the list
for(list<int>::iterator itr = ++numbersToTest.begin(); *itr < sqrt((float) input); itr++)
{
int tmp = *itr;
numbersToTest.remove_if(bind2nd(is_multiple(), *itr));
itr = find(numbersToTest.begin(), numbersToTest.end(), tmp); //remove_if invalidates iterator
// so find it again. kind of ugly
}
// output primes
for(list<int>::iterator itr = numbersToTest.begin(); itr != --numbersToTest.end(); itr++)
cout << *itr << "\t";
system("PAUSE");
return 0;
}
Any advice on how to improve this would be welcome by the way.
Here is my code. When working on a big number, it's very slow!
It can calculate all prime numbers with in the number you input!
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
int main()
{
int m;
int n=0;
char ch;
fstream fp;
cout<<"What prime numbers do you want get within? ";
if((cin>>m)==0)
{
cout<<"Bad input! Please try again!\n";
return 1;
}
if(m<2)
{
cout<<"There are no prime numbers within "<<m<<endl;
return 0;
}
else if(m==2)
{
fp.open("prime.txt",ios::in|ios::out|ios::trunc);//create a file can be writen and read. If the file exist, it will be overwriten.
fp<<"There are only 1 prime number within 2.\n";
fp<<"2\n";
fp.close();
cout<<"Congratulations! It has worked out!\n";
return 0;
}
else
{
int j;
int sq;
fp.open("prime.txt",ios::in|ios::out|ios::trunc);
fp<<"2\t\t";
n++;
for(int i=3;i<=m;i+=2)
{
sq=static_cast<int>(sqrt(i))+1;
fp.seekg(0,ios::beg);
fp>>j;
for(;j<sq;)
{
if(i%j==0)
{
break;
}
else
{
if((fp>>j)==NULL)
{
j=3;
}
}
}
if(j>=sq)
{
fp.seekg(0,ios::end);
fp<<i<<"\t\t";
n++;
if(n%4==0)
fp<<'\n';
}
}
fp.seekg(0,ios::end);
fp<<"\nThere are "<<n<<" prime number within "<<m<<".\n";
fp.close();
cout<<"Congratulations! It has worked out!\n";
return 0;
}
}
For one, you'd have less code (which is always a good thing!) if you didn't have special cases for 3, 5 and 7.
Also, you can avoid the special case for 2 if you just set num[b] = 2 and only test for divisibility by things in your array.
It looks like as you go around the main for() loop, the value of b increases.
Then, this results in a crash because you access memory off the end of your array:
for (int d = 0; d <= b; d++) {
c = num[d];
I think you need to get the algorithm clearer in your head and then approach the code again.
Running your code through a debugger, I've found that it crashes with a floating point exception at "if ((a % c) == 0)". The reason for this is that you haven't initialized anything in num, so you're doing "a % 0".
From what I know, in C/C++ int is a 16bit type so you cannot fit 1 million in it (limit is 2^16=32k). Try and declare "a" as long
I think the C standard says that int is at least as large as short and at most as large as long.
In practice int is 4 bytes, so it can hold numbers between -2^31 and 2^31-1.
Since this is for pedagogical purposes, I would suggest implementing the Sieve of Eratosthenes.
This should also be of interest to you: http://en.wikipedia.org/wiki/Primality_test
for(int currentInt=2; currentInt<=1000000; currentInt++)
{check = false; // Basically the idea for this for loop is to run checks against integers. This is the main for loop in this program. I re initialize check to false ( check is a bool declared above this. )
for( int arrayPrime=0; arrayPrime<currentPrime; arrayPrime++) // This for loop is used for checking the currentInt against previously found primes which are stored in the num array.
{ c=num[arrayPrime];
if ((currentInt%c)==0) { check = true;// second filter based on previous recorded primes in array
break;} // this is the check. I check the number against every stored value in the num array. If it's divisible by any of them, then bool check is set to true.
if ( currentInt == 2)
{ check = false; } // since i preset num[0] = 2 i make an exception for the number 2.
if (!check)
{
e=a;
if(currentPrime <= 100){
num[currentPrime]= currentInt;} // This if uses check to see if the currentInt is a prime.
currentPrime = currentPrime+1;} // increases the value of currentPrime ( previously b ) by one if !check.
if(currentPrime==prime)
{
write<<e<<endl;
break;} // if currentPrime == prime then write the currentInt into a txt file and break loop, ending the program.
Thanks for the advice polythinker =)
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
int main()
{
ifstream trial;
trial.open("C:\\Users\\User\\Documents\\trial.txt");
int prime, e;
trial>>prime;
ofstream write;
write.open("C:\\Users\\User\\Documents\\answer.txt");
int num[10000], currentPrime, c, primePrint;
bool check;
currentPrime=0;
num[currentPrime] = 2;
currentPrime=1;
for(int currentInt=2; currentInt<=1000000; currentInt++)
{check = false;
for( int arrayPrime=0; arrayPrime<currentPrime; arrayPrime++)
{ c=num[arrayPrime];
if ((currentInt%c)==0) { check = true;// second filter based on previous recorded primes in array
break;}
}
if (!check)
{ e=currentInt;
if( currentInt!= 2 ) {
num[currentPrime]= currentInt;}
currentPrime = currentPrime+1;}
if(currentPrime==prime)
{
write<<e<<endl;
break;}
}
trial.close();
write.close();
return 0;
}
This is the finalized version base on my original code. It works perfectly and if you want to increase the range of prime numbers simply increase the array number. Thanks for the help =)
Since you will need larger prime number values for later questions, I suggest you follow dreeves advice, and do a sieve. It is a very useful arrow to have in your quiver.