I'm new to C and I'm trying to convert decimal to binary.
The result is giving me an inverse number of what's required.
I tried to apply modulo on the result like I saw on other forums but I still get the same result.
Any help?
#include<stdio.h>
int main()
{
int number;
long int quotient, rem;
printf("Enter a number: ");
scanf("%d", &number);
quotient=number;
while (quotient!=0)
{
quotient=quotient/2;
rem=quotient%2;
printf("%ld", rem%10);
rem/=10;
}
}
I took an advice basing on a Print Function but still not sure if i understand it stills give me the same result. Please have a look.
#include<stdio.h>
void Print(int number,int base)
{
if (number >= base)
Print(number/base,base);
printf("%d",number%base);
}
int main()
{
int number;
long int quotient, rem;
printf("Enter a number: ");
scanf("%d", &number);
quotient=number;
while (quotient!=0)
{
quotient=quotient/2;
rem = quotient%2;
Print(rem, 2);
}
}
Just a small note because i forgot to say and I don't want you to go through the trouble.
The idea os to not use arrays.
Thanks
You can do it the "Last In First Out" way:
void Print(int number,int base)
{
if (number >= base)
Print(number/base,base);
printf("%d",number%base);
}
Then, from main, you can call it with any base between 2 and 10.
you shall various way to solve the problem.
process 1: just do right shift, check shifted result and print decised output.
int main()
{
int n, c, k;
printf("Enter an integer in decimal number system\n");
scanf("%d", &n);
printf("%d in binary number system is:\n", n);
for (c = 31; c >= 0; c--)
{
k = n >> c;
if (k & 1)
printf("1");
else
printf("0");
}
printf("\n");
return 0;
}
I'm trying to convert decimal to binary
You don't have anything decimal past the point you have scanned the input. You have a number. Numbers are not decimal or binary, they are just numbers. scanf has converted a decimal representation of some number to just a number for you.
Once you have a number you want to obtain its binary representstion. Once again, you have nothing decimal at hand.
Now ask yourself whether division by 10 you have found at some dark corner of the Internet could possibly be correct here.
(This answer is intentionally left unfinished)
long int decimalNumber,remainder,quotient;
int binaryNumber[100],i=1,j;
printf("Enter any decimal number: ");
scanf("%ld",&decimalNumber);
quotient = decimalNumber;
while(quotient!=0){
binaryNumber[i++]= quotient % 2;
quotient = quotient / 2;
}
printf("Equivalent binary value of decimal number %d: ",decimalNumber);
for(j = i -1 ;j> 0;j--)
printf("%d",binaryNumber[j]);
Here you go from your own code I was able to correct misleads and provide a correct display of the binary number.
#include<stdio.h>
int main()
{
long int decimal, quotient;
int binarynumber[1024];
const int base = 2;
printf("Enter a number: ");
scanf("%ld", &decimal);
printf("%d in binary: ", decimal);
quotient = decimal;
int i=1;
while (quotient!=0)
{
binarynumber[i++]=quotient%base;
quotient/=base;
}
for(int j=i; j>0; --j){
printf("%d",binarynumber[j]);
}
printf("\n");
return 0;
}
You were correct to have a decimal number variable, I called it decimal to avoid confusion. However, you can just store the input of the decimal number inside of quotient, it will work just the same.
I added the base number variable base, which should be a constant in my opinion, instead of the modulus operator plus base, which is %2 in your code.
You should have a variable, you had rem, binarynumber in this code - to store it all in and then reverse the numbers in this variable like in the for loop provided in the code. I though it better to store it in an array instead of creating a confusion with an additional variable called rem.
I don't entierly know what you wanted to do with rem/=10;, so I worked around that.
You were correct to use long int for the quotient, however, long int in many cases, is the same as int.
On many (but not all) C and C++ implementations, a long is larger than
an int. Most compilers use a 32 bit int which has the same size and representation
as a long. Reference
One more thing, you used to divide by base and store into the quotient (in your code quotient=quotient/2;) before retrieving the modulus answer, which resulted in a incorrect modulus, an incorrect remainder that is (in your code rem=quotient%2;). It retrieved the reminder of the next number.
Hope this is clear.
Try this code.
int number;
printf("Enter a number: ");
scanf("%d", &number);
printf("%d",decimal_binary(number));
int decimal_binary(int n) /* Function to convert decimal to binary.*/
{
int rem, i=1, binary=0;
while (n!=0)
{
rem=n%2;
n/=2;
binary+=rem*i;
i*=10;
}
return binary;
}
Related
#include <stdio.h>
#include <conio.h>
int getn(int n, int i);
int main()
{
int n, i;
getn(n, i);
getch();
return 0;
}
int getn(int n, int i)
{
int even = 0;
int odd = 1;
int avg;
printf("Enter ten integers: \n");
for (i = 1 ; i <= 10 ; i++)
{
printf("Integer %d: ", i);
scanf("%d", &n);
if ( n % 2 == 0 )
{
even = even + n;
}
else
{
odd = odd * n;
}
}
avg = even / 10;
printf("\n\nAverage of even numbers: %d", avg);
printf("\nProduct of odd numbers: %d", odd);
}
It seems the even calculations worked but when it comes to odd it gives the wrong answer. Please help
Our instructor wants us to use looping or iterations. No arrays. Please help me
First, your C code needs some correction:
at least give the prototype of getn before using it
getn is defined to return an int and doesn't return anything. Either replace int with void or return a value.
Second,
Your code computes the product of ten numbers, if this product is too big, it cannot be store as-is in an int. For example, it works well if you enter ten times number 3, the result is 59049, but if you enter ten times number 23, it will answer 1551643729 which is wrong because 23^10=41426511213649 but that can't be stored in an int. This is known as arithmetic overflow.
Your average is bad, because you sum ints, but the average is (in general) a rational number (average(2,3)=2.5 isn't it ?). So double avg = out/10.0; (means compute a floating division) and printf("Average %f\n",avg); would be better.
I've tried making a calculator that first reads the input from the user and then decides wheter the input is in binary or in decimal and then converts it.
i got almost everything but can't come up with the identifier! here's the code that i got:
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
int a;
char num[100];
int number[100];
int decimal_binary (int n);
int binary_decimal (int n);
void errorcode(void);
bool bin, decim;
int main (){
bin (false);
decim (false);
printf ("enter a number: ");
gets (num);
a = strlen(num);
if (a > 8){
errorcode();
//printf("That is an invalid number!");
//exit(45);
}
for (int i=0; i < a; i++){
number[i] = num[i] -'0';
printf("%d", number[i]);
}
int decimal_binary(int n){
int rem, i=1, binary = 0;
while (n != 0)
{
rem =n%2;
n/=2;
binary+=rem *i;
i*=10;
}
return binary;
}
int binary_decimal(int n)
{
int decimal = 0, i=0, rem;
while (n!-0){
rem = n%10;
n/=10;
decimal += rem *pow(2,i);
++i;
}
return decimal;
}
}
void errorcode(void){
printf("That is an invalid number!");
exit(45);
}
There is no such way to detect whether the number entered was binary or decimal just by analysing the characters of the number entered. However, if you study the Microsoft Windows calculator application that ships along with the OS, the "programmer" type of calculator takes an input whether the entered number is binary or decimal from the user, then internally in its code it would check whether the entered number was a valid binary or decimal number.
In short, your code will have to tell the user to specify what number is entered.
I would recommend studying the Microsoft calculator application's "programmer" type calc in order to help you understand what you want to achieve.
I believe the correct answer to this question is that binary numbers can be identified with the 0b prefix. Ex: 0b11111111 is the byte 0xFF, or 255 decimal. Notice the 0x prefix on the hex number. Decimal numbers have no prefix.. In fact, if you lead your 'decimal' number with a zero, the compiler will think that it is an octal number and treat it as base 8.
This is the C Program I have written to convert a Decimal number to it's equivalent Binary number. I have used Stack (implemented using array) and the following algorithm:
Number is divided and remainders are pushed in stack.
Remainders are popped one at a time and converted into Binary
The Problem is that the program works fine for numbers up to 3, after that from 4 on wards, each Binary Number comes one less than the actual number.
// Decimal to Binary conversion using Stack
#include<stdio.h>
#include<math.h>
#define max 20
int top=-1, stk[max];
void push(int);
int pop(void);
int main()
{
int i,num,x,flag=0,s, bin=0, factor;
printf("Enter any decimal number: ");
scanf("%d",&num);
while(num>0)
{
if(num==1)
push(num);
else
{
x = num%2;
push(x);
}
num/=2;
flag++;
}
for(i=0;i<flag;i++)
{
s = pop();
bin = bin + s*pow(10,(flag-1-i));
}
printf("\nEquivalent Binary number is --> %d",bin);
return 0;
}
void push(int n)
{
if(top == max-1)
{
printf("Error! Overflow");
return;
}
stk[++top] = n;
}
int pop(void)
{
int y;
if(top == -1)
{
printf("Error! Underflow");
return;
}
y = stk[top];
top = top-1;
return y;
}
Will anybody help me by finding the logical flaw?
Thank You
My answer is your program is unnecessarily complicated.
#include<stdio.h>
int main()
{
unsigned num, i, zeros = 0;
printf("Enter a decimal number: ");
scanf("%u", &num);
printf ("Decimal %u in binary is ", num);
for (i=sizeof(unsigned)*8; i>0; i--)
{
if ((int)num < 0) // get MSB
zeros = printf ("1"); // cancel 0-suppresion
else if (zeros)
printf ("0");
num <<= 1;
}
printf ("\n");
return 0;
}
The function pow return a double that can have a 9999999... after the decimal point, which is rounded to the floor when it is casted to int, you can fix your problem using ceil() function, that returns the smallest integer value greater than or equal the argument, like this.
bin = bin + ceil(s*pow(10,(flag-1-i)));
//C Program to convert Decimal to binary using Stack
#include<stdio.h>
#define max 100
int stack[max],top=-1,i,x;
/*------ Function Prototype------------*/
void push (int x)
{
++top;
stack [top] = x;
}
int pop ()
{
return stack[top];
}
/*-------------------------------------*/
void main()
{
int num, total = 0,item;
printf( "Please enter a decimal: ");
scanf("%d",&num);
while(num > 0)
{
total = num % 2;
push(total);
num /= 2;
}
for(i=top;top>-1;top--)
{
item = pop ();
printf("%d",item);
}
}
Here is a simpler version of your above program
int main(){
int n,remainder;
printf("Enter a decimal number:");
scanf("%d",&n);
while(n!=0){
remainder = n%2;
n = n/2;
push(remainder); // inserting in stack
}
display(); // displaying the stack elements
}
reference of above code
C program to Convert Decimal number into Binary using Stack
So I've done the math on several numbers, and this appears to be correct. I would agree with others that this is needlessly complicated, but that is not causing your issues on it's own, it's just making them harder to find.
So the output of this program appears correct, from a logical standpoint. Lets look into other potential issues:
You're indexing an array with an int that you initialize to -1
This is bad practice, and unnecessary. Array indexes in C can never be negative, so the compiler will assume this is an unsigned number, so if you have a 32 bit processor, it will assume you're trying to get array[2^32 - 1], which is not what you want. Always use a unsigned value for array indexes
What MIGHT be happening, and I'm not certain, is that your compiler is doing something with this behind the scenes which is screwing up your program, it's really hard to say. But it's probably attempting to convert your negative number into an unsigned int before you do your addition. Fix this by changing your declaration of top to:
unsigned int top = 0;
and changing where you access top from:
stk[++top] = n;
to
stk[top++] = n;
You will also have to change
y = stk[top];
top = top-1;
to
top = top-1;
y = stk[top];
I'd say start there. I'd also suggest removing the pow line, and just individually printing each piece of the array, because it will output in the same way, and you already have all the info there ie.
PRINTF("%d%d%d",stk[2],stk[1],stk[0]);
The program below is sufficent enouhgh to find the length of any string length that is given to the input, however, i need to find the length of an integer variable, rather than a string.
Entering a number to this does work, but not if i scan s as a int type.
int main()
{
char s[1000];
char i;
int u=5;
do
{
char s[1000];
char i;
int u=5;
system("cls");
printf("Enter a string: ");
scanf("%s",s);
for(i=0; s[i]!='\0'; ++i);
printf("Length of string: %d",i);
getch();
}
while(u==5);
getch();
}
So all i need is either this little program modified to accept intger variables, or a way to transform a calculated int variable into a string.
Any ideas?
Edit: Length = Amount of characters so 25 has 2, 3456 has 4 etc
You can calculate the length of n in base m with the formula:
ceil(log(n + 1, m))
Where ceil is the ceiling (round up) function, and log(a, b) is logarithms of a in base b.
You may use the below code to find the number of digits of an integer:
int count=0;
while(n!=0)
{
n/=10;
++count;
}
Where n is your input integer and count will be the it's length.
If you want to read an integer as an integer i,e with %d and count number of digits in that integer, have a look at below code snippet.
int no,length=0;
printf("Enter number");
scanf("%d",&no);
while(no!=0)
{
length+=1;
no=no%10;
}
printf("Length=%d",length);
To determine the number of characters to print a decimal number (assuming value is the int), you could do the following:
int intlen = 0;
if (value < 0) // for negative values, allow a char for the minus sign
{
value = -value;
++intlen;
}
while (value >= 10) // as long as the value is 1 or more,
{
value /= 10; // divide by 10,
++intlen; // ...and add one to the length
}
++intlen; // add one for last digit (even if it's zero)
It's probably easier to use the ceil/log function described above, but this one does not require the math library (if that is an issue)
Another brute-force approach would be as follows:
char temp[12];
int intlen = sprintf(temp,"%i",value);
This utilizes the fact that sprintf returns the number of characters placed in the string buffer.
#include<stdio.h>
main()
{
int count=1,n;
scanf("%d",&n);
while(n/=10)
count++;
printf("result=%d",count);
}
count gives the number of digits in number n
The code is giving false answers. İf number equals 42, it turns it to 101010. Ok, it is true. But if number equals 4, it turns it to 99. I didn't find the mistake. How can i fix the code?
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
int i,digit,number=4;
long long bin= 0LL;
i=0;
while(number>0)
{
digit=number%2;
bin+=digit*(int)pow(10,i);
number/=2;
i++;
}
printf("%d ",bin);
getch();
}
Stop using floating point calculations for this. You are subject to the vagaries of floating point. When I ran your program with my compiler, the output was 100. But I guess your compiler treated the floating point pow differently.
A simple change to make the code behave, and use integer arithmetic only, would be like this:
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
int digit,number=4;
long long scale,bin= 0LL;
scale=1;
while(number>0)
{
digit=number%2;
bin+=digit*scale;
number/=2;
scale*=10;
}
printf("%lld ",bin);
getch();
}
But I'd rather see the binary built up in a string rather than an integer.
You can use a simpler and easier approach to convert decimal to binary number system.
#include <stdio.h>
int main()
{
long long decimal, tempDecimal, binary;
int rem, place = 1;
binary = 0;
/*
* Reads decimal number from user
*/
printf("Enter any decimal number: ");
scanf("%lld", &decimal);
tempDecimal = decimal;
/*
* Converts the decimal number to binary number
*/
while(tempDecimal!=0)
{
rem = tempDecimal % 2;
binary = (rem * place) + binary;
tempDecimal /= 2;
place *= 10;
}
printf("\nDecimal number = %lld\n", decimal);
printf("Binary number = %lld", binary);
return 0;
}