I have an assignment to make a program that should convert a number from it's integer value to a binary value. For some reason my array is always filled with zeroes and won't add "1"'s from my if statements. I know there are probably solutions to this assignment on internet but I would like to understand what is problem with my code. Any help is appreciated.
Here is what I tried:
#include <iostream>
/*Write a code that will enable input of one real number in order to write out it's binary equivalent.*/
int main() {
int number;
int binaryNumber[32] = { 0 };
std::cout << "Enter your number: ";
std::cin >> number;
while (number > 0) {
int i = 0;
if ((number / 10) % 2 == 0) {
binaryNumber[i] = 0;
}
if ((number / 10) % 2 != 0) {
binaryNumber[i] = 1;
}
number = number / 10;
i++;
}
for (int i = 31; i >= 0; i--) {
std::cout << binaryNumber[i];
}
return 0;
}
You need to remove number/10 in both the if statements. Instead, just use number. you need the last digit every time to get the ith bit.
Moreover, you need to just half the number in every iteration rather than doing it /10.
// Updated Code
int main() {
int number;
int binaryNumber[32] = { 0 };
std::cout << "Enter your number: ";
std::cin >> number;
int i = 0;
while (number > 0) {
if (number % 2 == 0) {
binaryNumber[i] = 0;
}
if (number % 2 != 0) {
binaryNumber[i] = 1;
}
number = number / 2;
i++;
}
for (int i = 31; i >= 0; i--) {
std::cout << binaryNumber[i];
}
return 0;
}
The first thing is the variable 'i' in the while loop. Consider it more precisely: every time you iterate over it, 'i' is recreated again and assigned the value of zero. It's the basics of the language itself.
The most relevant mistake is logic of your program. Each iteration we must take the remainder of division by 2, and then divide our number by 2.
The correct code is:
#include <iostream>
int main()
{
int x = 8;
bool repr[32]{};
int p = 0;
while(x)
{
repr[p] = x % 2;
++p;
x /= 2;
}
for(int i = 31; i >= 0; --i)
std::cout << repr[i];
return 0;
}
... is always filled with zeroes ... I would like to understand what is problem with my code
int i = 0; must be before the while, having it inside you only set the index 0 of the array in your loop because i always values 0.
But there are several other problems in your code :
using int binaryNumber[32] you suppose your int are on 32bits. Do not use 32 but sizeof(int)*CHAR_BIT, and the same for your last loop in case you want to also write 0 on the left of the first 1
you look at the value of (number / 10) % 2, you must look at the value of number % 2
it is useless to do the test then its reverse, just use else, or better remove the two ifs and just do binaryNumber[i] = number & 1;
number = number / 10; is the right way when you want to produce the value in decimal, in binary you have to divide by 2
in for (int i = 31; i >= 0; i--) { except for numbers needing 32 bits you will write useless 0 on the left, why not using the value of i from the while ?
There are some logical errors in your code.
You have taken (number/10) % 2, instead, you have to take (number %2 ) as you want the remainder.
Instead of taking i = 31, you should use this logic so you can print the following binary in reverse order:
for (int j = i - 1; j >= 0; j--)
{
cout << BinaryNumb[j];
}
Here is the code to convert an integer to its binary equivalent:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
// function to convert integer to binary
void DecBinary(int n)
{
// Array to store binary number
int BinaryNumb[32];
int i = 0;
while (n > 0)
{
// Storing remainder in array
BinaryNumb[i] = n % 2;
n = n / 2;
i++;
}
// Printing array in reverse order
for (int j = i - 1; j >= 0; j--)
{
cout << BinaryNumb[j];
}
}
// Main Program
int main()
{
int testcase;
//Loop is optional
for(int i = 0; i < testcase; i++)
{
cin >> n;
DecToBinary(n);
}
return 0;
}
Related
I should mention the purpose of this code is to tackle a leading zero scenario when finding date palindromes in dates in format MMDDYYY.
Here is the code.
#include <iostream>
using namespace std;
unsigned numDigits (unsigned num)//this works
{
if (num < 10) return 1;
return 1+ numDigits(num/10);
}
int main ()
{
unsigned date = 1111110;//01/11/1110(jan 11th of 1110 is palindrome)
cout<<numDigits(date)<<"num of dig"<<endl;
if (numDigits(date) == 7)
{
unsigned array[8];
unsigned number = date;
unsigned revArr[8];
for (int h = 7; h >= 0; h--) //this pops array withdate
{
array[h] = number % 10;
number /= 10;
cout<<array[h]<<endl;
}
cout<<"vs"<<endl;
for (int i = 0; i < 8; i++) //this pops revarray withdate
{
revArr[i] = number % 10;
number /= 10;
cout<<array[i]<<endl;
}
for (int j = 0; j < 8; j++)
{
if (array[j] == revArr[j])
{
cout<<j<<"th digit are" <<" equal"<<endl;
}
}
}
return 0;
}
In this case both of the arrays are identical, I don't underdtdanwd why array[0] == revArr[0] but array[1] != revArr[1] and so on but array[7] == revArr[7] again... its boggling my mind.
The loops traverse all elements of the array. Even when the expression number /= 10 is equal to 0. In this case the zero is stored in the array elements because 0 / 10 gives again 0.
Before the second loop write
number = date;
I am writing a code to give numbers in a line and the inputs finish with zero then wirtes the highest power of 2 smaller or equal the inputs in a line.
it doesn't work.
#include<iostream>
#include<stdio.h>
using namespace std;
int highestPowerof2( int n)
{
static int result = 0;
for (static int i=n; i>=1; i--)
{
if ((i & (i-1)) == 0)
{
result = i;
break;
}
}
return result;
}
int main() {
static int num ;
do{
cin>>num ;
}
while(num=!0);
cout<<highestPowerof2(num)<<"\n";
return 0;
}
The most surprising thing in your code is this:
do{
cin>>num ;
}
while(num=!0);
You keep reading num from user input until num == 0. I have to admit that I dont really understand the rest of your code, but for num == 0 calling the function highestPowerof2(num) will always result in 0.
Perhaps you wanted to repeat the program until the user decides to quit, that could be
do{
cin>>num ;
cout<<highestPowerof2(num)<<"\n";
} while(num=!0);
PS: the other "surprising" thing is that you use static in places where it does not really make sense. Better simply remove it.
Here is another approach that is a little bit faster for large n. For example if n = 2^31 - 1, then the original loop would need to iterate 2^30 - 1 = 1,073,741,823 times, whereas this loop only needs a single iteration (provided sizeof(int) == 4):
#include <iostream>
#include <stdio.h>
using namespace std;
int highestPowerof2( int n)
{
if (n < 0) return 0;
int result = 0;
int num_bits = sizeof(int) * 8;
unsigned int i = 1 << (num_bits - 1);
while(i > 0) {
if (n >= i) return i;
i >>= 1;
}
return 0;
}
int main() {
int num ;
while (1) {
cin >> num;
cout << highestPowerof2(num) << "\n";
if (num == 0) break;
}
return 0;
}
I have to create a program which calculates the factorial of any number, the problem is if I input any number above 20 it just returns that number. What in my else if statement could be causing this and is there a better way to solve this? ( this function is called in main and works if num <= 20)
void factorial() {
//User input for number
long long num;
std::cout << "Input any positive integer to find its factorial: ";
std::cin >> num;
unsigned long long numFact = 1;
if (num <= 20) {
while (num > 0) {
numFact = numFact * num;
num = num - 1;
}
std::cout << numFact;
}
else if (num > 20) {
std::vector<int> multFactorial;
//stores num as seperate elements in vector multFactorial
while (num > 0) {
int remain = num % 10;
num = num / 10;
multFactorial.insert(multFactorial.begin(), remain);
}
std::vector<int> answer;
std::vector<int> answerFinal;
//Manually multiplies elements in multFactorial
//Then adds new vectors created by multiplying to get final answer
//Repeats until factorial is solved
//Ex: 21 * 20; 0 * 1 and 0 * 2 stored as {0 , 0}
//2*1 and 2*2 stored as {4, 2, 0}
//Vectors will be addes to get {4, 2, 0} and then that will be multiplied
by 19 until num = 1
while (num > 1) {
for (int i = multFactorial.size() - 1; i >= 0; i--) {
int remain1 = ((num - 1) % 10) * multFactorial[i];
answer.insert(answer.begin(), remain1);
int remain2 = (((num - 1) / 10) * multFactorial[i]);
answerFinal.insert(answerFinal.begin(), remain2);
}
answerFinal.insert(answerFinal.begin(), 0);
//Adds vectors to get final value seperate as digits
for (int i = multFactorial.size() - 1; i >= 0; i--) {
multFactorial[i] = answer[i] + answerFinal[i];
}
num = num - 1;
}
//Prints what should be the factorial of the number input
for (size_t i = 0; i < multFactorial.size(); i++) {
std::cout << multFactorial[i];
}
}
}
Factorials of large numbers results in huge numbers. This can be accommodated in languages like C, C++ etc by putting the results into arbitrary length strings.
Here is an algorithm for that - similar to yours.
https://www.geeksforgeeks.org/factorial-large-number/
Best advice is to check your code against this.
Use a debugger if you have one and step through the code line by line.
If not print out intermediate results and compare with expected.
EDIT: As per review comment, the code at above ref is similar to below- just in case link is broken in future.
// C++ program to compute factorial of big numbers
#include<iostream>
using namespace std;
// Maximum number of digits in output
#define MAX 100 // change to whatever value you need
int multiply(int x, int res[], int res_size);
// Calculate factorial of large number
void factorial(int n)
{
int res[MAX];
// Initialize result
res[0] = 1;
int res_size = 1;
// Apply factorial formula
for (int x=2; x<=n; x++)
res_size = multiply(x, res, res_size);
// print out the result
cout << "Factorial is \n";
for (int i=res_size-1; i>=0; i--)
cout << res[i];
}
// Multiplies x with the number represented by res[].
// res_size is size of res[] or number of digits in the
// number represented by res[].
int multiply(int x, int res[], int res_size)
{
int carry = 0; // Initialize carry
// One by one multiply n with individual digits of res[]
for (int i=0; i<res_size; i++)
{
int prod = res[i] * x + carry;
// Store last digit of 'prod' in res[]
res[i] = prod % 10;
// Put rest in carry
carry = prod/10;
}
// Put carry in res and increase result size
while (carry)
{
res[res_size] = carry%10;
carry = carry/10;
res_size++;
}
return res_size;
}
// Main program
int main()
{
//put code here to read a number
factorial(50); // take 50 for example
return 0;
}
I'm trying to get all prime numbers in the range of 2 and the entered value using this c++ code :
#include<iostream>
using namespace std;
int main() {
int num = 0;
int result = 0;
cin >> num;
for (int i = 2; i <= num; i++) {
for (int b = 2; b <= num; b++) {
result = i % b;
if (result == 0) {
result = b;
break;
}
}
cout << result<< endl <<;
}
}
the problem is that I think am getting close to the logic, but those threes and twos keep showing up between the prime numbers. What am I doing wrong?
I've fixed your code and added comments where I did the changes
The key here is to understand that you need to check all the numbers smaller then "i" if one of them dividing "i", if so mark the number as not prime and break (the break is only optimization)
Then print only those who passed the "test" (originally you printed everything)
#include <iostream>
using namespace std;
#include<iostream>
using namespace std;
int main()
{
int num = 0;
int result = 0;
cin >> num;
for (int i = 2; i <= num; i++) {
bool isPrime = true; // Assume the number is prime
for (int b = 2; b < i; b++) { // Run only till "i-1" not "num"
result = i % b;
if (result == 0) {
isPrime = false; // if found some dividor, number nut prime
break;
}
}
if (isPrime) // print only primes
cout << i << endl;
}
}
Many answers have been given which explains how to do it. None have answered the question:
What am I doing wrong?
So I'll give that a try.
#include<iostream>
using namespace std;
int main() {
int num = 0;
int result = 0;
cin >> num;
for (int i = 2; i <= num; i++) {
for (int b = 2; b <= num; b++) { // wrong: use b < i instead of b <= num
result = i % b;
if (result == 0) {
result = b; // wrong: why assign result the value of b?
// just remove this line
break;
}
}
cout << result<< endl <<; // wrong: you need a if-condtion before you print
// if (result != 0) cout << i << endl;
}
}
You have multiple errors in your code.
Simplest algorithm (not the most optimal though) is for checking whether N is prim is just to check whether it doesn't have any dividers in range [2; N-1].
Here is working version:
int main() {
int num = 0;
cin >> num;
for (int i = 2; i <= num; i++) {
bool bIsPrime = true;
for (int b = 2; bIsPrime && b < i; b++) {
if (i % b == 0) {
bIsPrime = false;
}
}
if (bIsPrime) {
cout << i << endl;
}
}
}
I would suggest pulling out the logic of determining whether a number is a prime to a separate function, call the function from main and then create output accordingly.
// Declare the function
bool is_prime(int num);
Then, simplify the for loop to:
for (int i = 2; i <= num; i++) {
if ( is_prime(i) )
{
cout << i << " is a prime.\n";
}
}
And then implement is_prime:
bool is_prime(int num)
{
// If the number is even, return true if the number is 2 else false.
if ( num % 2 == 0 )
{
return (num == 2);
}
int stopAt = (int)sqrt(num);
// Start the number to divide by with 3 and increment it by 2.
for (int b = 3; b <= stopAt; b += 2)
{
// If the given number is divisible by b, it is not a prime
if ( num % b == 0 )
{
return false;
}
}
// The given number is not divisible by any of the numbers up to
// sqrt(num). It is a prime
return true;
}
I can pretty much guess its academic task :)
So here the think for prime numbers there are many methods to "get primes bf number" some are better some worse.
Erosthenes Sieve - is one of them, its pretty simple concept, but quite a bit more efficient in case of big numbers (like few milions), since OopsUser version is correct you can try and see for yourself what version is better
void main() {
int upperBound;
cin >> upperBound;
int upperBoundSquareRoot = (int)sqrt((double)upperBound);
bool *isComposite = new bool[upperBound + 1]; // create table
memset(isComposite, 0, sizeof(bool) * (upperBound + 1)); // set all to 0
for (int m = 2; m <= upperBoundSquareRoot; m++) {
if (!isComposite[m]) { // if not prime
cout << m << " ";
for (int k = m * m; k <= upperBound; k += m) // set all multiplies
isComposite[k] = true;
}
}
for (int m = upperBoundSquareRoot; m <= upperBound; m++) // print results
if (!isComposite[m])
cout << m << " ";
delete [] isComposite; // clean table
}
Small note, tho i took simple implementation code for Sive from here (writing this note so its not illegal, truth be told wanted to show its easy to find)
The program i am designing is for an assignment, but as a do distant learning it is not easy finding a solution.
The program that I have to create must first ask user for an unsigned long int and then break that number down to each digit without repeating number (for example 3344 the program should list 3 and 4), my program just lists all digits. After they have been listed the position of that digits needs to be dispayed with the position (digit at the right is position 0). Then the program should be "reconstruct" to make the original unsigned long int.
An example of what it should look like :
7377683
3 : 0 5
6 : 2
7 : 3 4 6
8 : 1
7377683
The code that i am using currently :
#include <iostream>
using namespace std;
int main()
{
unsigned long int number;
cout << "Enter an integer " << endl;
cin >> number;
for(int i=0; i<10 ; i++)
{
if (number > 0)
{
cout << number%10 << " : " << i; //output digit and position
cout << "\n";
number /= 10;
}
}
return 0;
}
I cannot use arrays or strings to complete this task and that is what i am finding challenging.
You could store digit positions in a decimal bitmask type thing.
unsigned long n, digits[10]{};
// Input
std::cin >> n;
// Break down
for (int i = 1; n; i *= 10, n /= 10)
digits[n % 10] += i;
// Reconstruct and print digit positions
for (int i = 0; i < 10; i++) {
if (!digits[i])
continue;
n += digits[i] * i;
std::cout << i << ":";
for (int j = 0; digits[i]; j++, digits[i] /= 10)
if (digits[i] % 10)
std::cout << " " << j;
std::cout << std::endl;
}
// Output
std::cout << n;
It's kinda neat because you don't need to know how many digits your number has. Also, you could construct the new number and output the positions of all digits in the same loop which you are breaking it down, thus removing the need to store the digits anywhere, but that feels like cheating.
Since you can't use arrays or strings you can probably get away with using an integral type as a bitmap. Any time you output a number in your loop set a bit in the bitmap that corresponds to that number. Then when you need to output that number you check to see if that bit is set and if it is you skip printing it out. Something like the following maybe.
for (int mask = 0, i = 0; i<10; i++)
{
if (number > 0)
{
int value = number % 10;
if ((mask & (1 << value)) == 0)
{
cout << value << " : " << i << endl; //output digit and position
mask |= 1 << value;
}
number /= 10;
}
}
Taking a number down into individual digits works like this:
int number = 4711;
vector<int> v;
while(number > 0)
{
int digit = number % 10;
number /= 10;
v.push_back(digit);
}
Putting it back together again into an integer (we need to go "backwards", as the digits come out "back to front" in the above code)
int number = 0;
for(int i = v.size()-1; i >= 0; i--)
{
number *= 10;
number += v[i];
}
I'm intentionally not showing a complete program to solve your problem, since part of learning programming is to learn how to solve problems. But you sometimes need a few "steps" on the way.
Something like this would solve it with arrays:
int array[10][10] = { { 0 } }; // Position of each digit.
int count[10] = { 0 }; // Number of each digit
int number = 4711;
int pos = 0;
while(number > 0)
{
int digit = number % 10;
number /= 10;
count[digit]++;
array[digit][count[digit]] = pos;
pos++;
}
I'm leaving it to you to fill in the rest of the code (to print and reassemble the number). [The above code doesn't cope with the number zero].
This is the working solution which address to the most crucial problem in your question:
int number = 7377683;
int temp = number;
int pos = 0;
int counter = 0;
int currNum;
int uniqueCount = 0;
Added: Codes to check number of unique digits in number:
for (int x=0; x<9; x++)
for (int y=temp; y>0; y/=10)
if (y%10 == x)
{
uniqueCount ++;
break;
}
Codes to generate the output of every unique elements and positions:
for (int y=0; y<uniqueCount; y++)
{
pos = counter;
currNum = number%10;
cout << temp%10 << " : ";
for (int x=temp; x>0; x/=10)
{
if (temp%10 == currNum)
cout << pos << " ";
pos++;
temp /= 10;
}
counter++;
number /=10;
temp = number;
cout << endl << endl;
}
Program Output:
3 : 0 5
8 : 1
6 : 2
7 : 3 4 6
This solution is using the most basic construct without array (according to your requirements).