I am trying to use the following algorithm to convert a decimal number to a binary number in C. I don't understand why it doesn't work properly for some inputs (e.g. for 1993 I get 1420076519).
int aux=x;
long bin=0;
while (aux>0)
{
bin=bin*10+aux%2;
aux=aux/2;
}
printf("%d in decimal is %ld in binary.", x, bin);
When you print a long you dont print the binary. The best way to convert to binary or show the binary representation of a decimal number is by storing it in a string. Bellow is a solution offered in a another SO answer
void getBin(int num, char *str)
{
*(str+5) = '\0';
int mask = 0x10 << 1;
while(mask >>= 1)
*str++ = !!(mask & num) + '0';
}
If you know the algorithm there's no reason not to use itoa
http://www.cplusplus.com/reference/clibrary/cstdlib/itoa/
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int n;
char output[100];
printf("Enter a number: ");
scanf("%d", &n);
itoa(n, output, 2); //2 means base two, you can put any other number here
printf("The number %d is %s in binary.", n, output);
return 0;
}
How does the conversion works?
/* Example:
125(10) -----> ?(2) 125 |_2
-1- 62 |_2
-0- 31 |_2
-1- 15 |_2
-1- 7 |_2
-1- 3 |_2
-1- 1 */
So in this example the binary number for 125(10) is 1111101(2), and this is the process I describe in my function.
/* Functions declaration (Prototype) */
int wordCalculator( int * const word, long int number, int base );
int main( void )
{
int i, base;
int word[ 32 ];
unsigned long int number;
printf( "Enter the decimal number to be converted: " );
scanf( "%ld", &number );
printf( "\nEnter the new base: " );
scanf( "%d", &base );
i = wordCalculator( word, number, base );
printf( "The number is: " );
for(; i >= 0; i--){
if ( word[ i ] <= 9)
printf( "%d", word[ i ] );
else
/* 65 represents A in ASCII code. */
printf( "%c", ( 65 - 10 + word[ i ] ) );
}
printf( "\n" );
}
int wordCalculator( int * const word, long int number, int base )
{
unsigned long int result = number;
int i, difference;
i = 0;
do{
difference = result % base;
result /= base;
*( word + i ) = difference;
i++;
if ( result < base )
*( word + i ) = result;
} while( result >= base );
return i;
}
I think the shortest answer is
char* getBinary(int n,char *s)
{
while(n>0)
{
*s=(n&1)+'0';
s++;
n>>=1;
}
*s='\0';
return s;
}
In the called function print it in reverse way .. because storing is done LSB to MSB
But we have to print MSB first then LSB
You should be using strings to store binary number. Following code should work for you.
#include <stdio.h>
#include <stdlib.h>
char *decimal_to_binary(int);
main()
{
int n, c, k;
char *pointer;
printf("Enter an integer in decimal number system\n");
scanf("%d",&n);
pointer = decimal_to_binary(n);
printf("Binary string of %d is: %s\n", n, pointer);
free(pointer);
return 0;
}
char *decimal_to_binary(int n)
{
int c, d, count;
char *pointer;
count = 0;
pointer = (char*)malloc(32+1);
if ( pointer == NULL )
exit(EXIT_FAILURE);
for ( c = 31 ; c >= 0 ; c-- )
{
d = n >> c;
if ( d & 1 )
*(pointer+count) = 1 + '0';
else
*(pointer+count) = 0 + '0';
count++;
}
*(pointer+count) = '\0';
return pointer;
}
You can use the below algorithm to convert Decimal number 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;
}
This is a recursive solution that i wrote, it is simple and works fine.
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int printBinary(int N)
{
if(N < 0){errno = EINVAL; return -1;}
if(N == 0)
printf("0");
else if(N == 1)
printf("1");
else
{
printBinary(N/2);
printf("%d", N%2);
}
return 0;
}
int main(int argc, char* argv[])
{
if(argc < 2)
{
fprintf(stderr, "usage: %s NUM\nWhere NUM is an integer number\n", argv[0]);
exit(EXIT_FAILURE);
}
errno = 0;
long NUM = strtol(argv[1], NULL, 10);
if(NUM == 0 && errno != 0)
{
perror("Error during number acquisition: ");
exit(EXIT_FAILURE);
}
if(NUM < 0)
{
printf("-");
printBinary(-NUM);
}
else
printBinary(NUM);
printf("\n");
return 0;
}
Related
Been working on this question for class. Not sure what I'm doing wrong.
Seems like I just don't have the correct format. My professor wants the output to look like "5!=1 * 2* 3* 4* 5=120"
Can someone help me with this? Below is what I have so far:
#include <iostream>
#include <stdio.h>
int main() {
int n, i, fact;
printf("Enter a positive integer: \n");
scanf("%d", &n);
if (n < 0)
printf("Error! Factorial of a negative number doesn't exist.");
else {
for( i = 1; i <= n; ++i) {
fact *= i;
n= n * (n-1);
}
printf("Factorial of %d = ", &n, &fact) ;
}
return 0;
}
remove #include <iostream> if it is the C code
Use functions.
Initialize local variables (you do not and it is undefined behaviour)
Compile C program using C compilers
unsigned long long fact(unsigned val, char *buff)
{
unsigned result = 1;
*buff++ = '1';
*buff = 0;
for(unsigned c = 2; c <= val; c++)
{
buff += sprintf(buff, "x%u", c);
result *= c;
}
return result;
}
int main(void)
{
unsigned x;
char y[1000];
unsigned long long res;
if(scanf("%u", &x) == 1){res = fact(x, y); printf("factoral(%u) = %s = %llu\n", x, y, res);}
else printf("Invalid number!!!\n");
}
or without printing steps
unsigned long long fact(unsigned val)
{
unsigned result;
switch(val)
{
case 0:
case 1:
result = 1;
break;
case 2:
result = 2;
break;
default:
result = 2;
while(val > 2) result *= val--;
break;
}
return result;
}
int main(void)
{
unsigned x;
if(scanf("%u", &x) == 1) printf("factioral(%u) = %llu\n", x, fact(x));
else printf("Invalid number!!!\n");
}
https://godbolt.org/z/Tf5431zco
For starters it does not make a sense to declare the variable n as having a signed integer type. It is better to declare it as having unsigned integer type. For example
unsigned int n, i, fact;
Secondly the variable fact was not initialized. You should initialize it by the value equal to 1.
So the above declaration could look like
unsigned int n, i;
unsigned long long fact = 1;
In this for loop
for( i = 1; i <= n; ++i) {
fact *= i;
n= n * (n-1);
}
the statement
n= n * (n-1);
does not make a sense and shall be removed.
In the printf call you have to use values of variables instead of pointers to the variables like
printf("Factorial of %u = %llu\n", n, fact) ;
Pay attention to that neither declaration from the header <iostream> is used in your program So whether it is a C program or a C++ program nevertheless remove this header.
Here is a demonstration C program.
#include <stdio.h>
int main( void )
{
unsigned int n = 0;
unsigned long long int fact = 1;
printf( "Enter a positive integer: " );
scanf( "%u", &n );
printf( "%u! = ", n );
for ( unsigned int i = 1; i <= n; i++ )
{
fact *= i;
if ( i != 1 ) printf( " * " );
printf( "%u", i );
}
printf( " = %llu\n", fact );
}
The program output might look like
Enter a positive integer: 5
5! = 1 * 2 * 3 * 4 * 5 = 120
If you are allowed to use only variables of the type int as you wrote in a comment to the answer then the program can look like
#include <stdio.h>
int main( void )
{
int n = 0;
int fact = 1;
printf( "Enter a positive integer: " );
scanf( "%d", &n );
if ( n < 0 )
{
puts( "Error! Factorial of a negative number doesn't exist.");
}
else
{
printf( "%d! = ", n );
for ( int i = 1; i <= n; i++ )
{
fact *= i;
if ( i != 1 ) printf( " * " );
printf( "%d", i );
}
printf( " = %d\n", fact );
}
}
To output multipliers in the reverse order like
5! = 5 * 4 * 3 * 2 * 1 = 120
rewrite the for loop the following way
for ( int i = n; i != 0; i-- )
{
fact *= i;
if ( i != n ) printf( " * " );
printf( "%d", i );
}
I am starter in the C.I wrote a simple code which are calculating how many digits are the entered Number and sum of entered number’s digits.Code calculating digit count right but sum of digits being given as ‘0’ every time.Could you say where is my error?thanks.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
int ndigit(int val) {
if (val == 0)
return 0;
int digit_count = 1;
while ((val = getchar() != '\n')) {
digit_count++;
val /= 10;
}
return digit_count;
}
int sumdigit(int number) {
int result = 0;
while ((number = getchar()) != '\n'){
result += number - '0';
}
return result;
}
int main()
{
int a;
printf("Bir tam sayi giriniz: \n");
a = getchar();
printf("Bu sayinin basamak sayisi =%d", ndigit(a));
printf("Bu sayinin basamak degeri toplami= %d", sumdigit(a));
}
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
The program does not make sense. To enter a number you should use one function. That is the number of digits and the sum of digits must be calculated for the same number.
This condition in the while statement
while ((val = getchar() != '\n')) {
is equivalent to
while ( ( val = ( getchar() != '\n' ) ) ) {
and as a result the integer val gets either 1 or 0.
As the variable val stores an internal representation of a character (for example its ASCII value) then this statement
val /= 10;
also does not make sense. Also the user can enter a non-digit character.
You should either use a character array for the entered number by means of calls of the function getchar or use the function scanf to enter a value of an integer object.
If to use a character array then the program can look the following way
#include <stdio.h>
char * get_number( char *number, size_t n )
{
size_t i = 0;
int c;
while( i + 1 < n && ( c = getchar() ) != EOF && c != '\n' && '0' <= c && c <= '9' )
{
number[i++] = c;
}
number[i] = '\0';
return number;
}
size_t ndigit( const char *number )
{
size_t n = 0;
while ( number[n] != '\0' ) ++n;
return n;
}
unsigned int sumdigit( const char *number )
{
unsigned int sum = 0;
while ( *number != '\0' )
{
sum += *number++ - '0';
}
return sum;
}
int main(void)
{
enum { N = 50 };
char number[N];
printf( "Bir tam sayi giriniz: " );
get_number( number, N );
printf( "Bu sayinin basamak sayisi = %zu\n", ndigit( number ) );
printf( "Bu sayinin basamak degeri toplami = %u\n", sumdigit( number ) );
return 0;
}
The program output might look like
Bir tam sayi giriniz: 123456789987654321
Bu sayinin basamak sayisi = 18
Bu sayinin basamak degeri toplami = 90
If to use an integer number then the program can look the following way
#include <stdio.h>
size_t ndigit( unsigned long long number )
{
const unsigned long long Base = 10;
size_t n = 0;
do
{
++n;
} while ( number /= Base );
return n;
}
unsigned int sumdigit( unsigned long long number )
{
const unsigned long long Base = 10;
unsigned int sum = 0;
do
{
sum += number % Base;
} while ( number /= Base );
return sum;
}
int main(void)
{
unsigned long long number = 0;
printf( "Bir tam sayi giriniz: " );
scanf( "%llu", &number );
printf( "Bu sayinin basamak sayisi = %zu\n", ndigit( number ) );
printf( "Bu sayinin basamak degeri toplami = %u\n", sumdigit( number ) );
return 0;
}
The program output might look as it is shown above.
Bir tam sayi giriniz: 123456789987654321
Bu sayinin basamak sayisi = 18
Bu sayinin basamak degeri toplami = 90
You code has 3 getchar() that are independent. Just use one getchar, either in main, or ndigit or sumdigit.
I propose, you should get the number in main function using scanf instead of getchar(), then pass the number as the argument to the other functions (ndigit and sumdigit). Because getchar reads character by character, and it does not guarantee the character is a digit or not.
The main function becomes:
int main () {
int num;
printf("enter the number: ");
scanf("%d", &num);
// calling the ndigit and sumdigit function:
printf("sum of digits = %d\n number of digits = %d\n", sumdigit(num), ndigit(num));
return 0;
}
For two function ndigit and sumdigit, you can change to:
ndigit function:
int ndigit(int number) {
number = abs(number); // calculate abs if the number is negative
if(number == 0)
return 1;
int count = 0;
do {
count++;
num /= 10;
} while(num != 0);
return count;
}
sumdigit function:
int sumdigit(int number) {
number = abs(number); // calculate abs if the number is negative
int sum = 0, temp = 0;
while (number != 0) {
temp = number % 10;
sum += temp;
number /= 10;
}
return sum;
}
The complete code:
#include <stdio.h>
#include <stdlib.h>
int ndigit(int number) {
number = abs(number); // calculate abs if the number is negative
if(number == 0)
return 1;
int count = 0;
do {
count++;
number /= 10;
} while(number != 0);
return count;
}
int sumdigit(int number) {
number = abs(number); // calculate abs if the number is negative
int sum = 0, temp = 0;
while (number != 0) {
temp = number % 10;
sum += temp;
number /= 10;
}
return sum;
}
int main () {
int num;
printf("enter the number: ");
scanf("%d", &num);
// calling the ndigit and sumdigit function:
printf("sum of digits = %d\nnumber of digits = %d\n", sumdigit(num), ndigit(num));
return 0;
}
The output of test:
enter the number: 222333
sum of digits = 15
number of digits = 6
After using scanf, change your sumdigit while loop to:
while (number > 0) {
result += number % 10;
number /= 10;
}
My program should convert a decimal number into a binary number.
The first for loop is for calculating the binary number.
The second loop puts the msb into the first element of the array.
It is an exercise and the msb has to be in the first element.
I do not understand where the mistake is, help is very much appreciated.
#include<stdio.h>
#include<stdlib.h>
int main(void){
int i;
int bits[16];
int bits_2[16];
int number;
int decimal;
int rest;
int msb;
int result=1;
printf( "Input number smaller than 65536: ");
scanf("%d", &decimal);
if(decimal >= 65536) {
printf( "\n\nincorrect input!");
return EXIT_FAILURE;
}
number=decimal;
for(i=0; result!=0; i++){
result = decimal / 2;
rest = result %2;
bits[i]=rest;
msb = i;
return msb;
}
printf("\n\n %d as binary number : ", number);
for(i=msb; bits[i]>=bits[0]; i--){
bits_2[msb-i] = bits[msb];
printf("%d", bits_2[msb-i]);
}
return 0;
}
result = number = decimal;
for(bits[0]=msb=i=0; result != 0; i++){
bits[i] = result % 2;
result = result / 2;
msb = i;
}
printf("\n\n %d as binary number : ", number);
for(i=msb; i >= 0; i--){
bits_2[msb-i] = bits[i];
printf("%d", bits_2[msb-i]);
}
This is your code with some changes to make it work (you can improve it)
#include<stdio.h>
#include<stdlib.h>
int main(void){
int i;
int bits[16];
int bits_2[16];
int number;
int decimal;
int rest;
int msb;
int result=1;
printf( "Input number smaller than 65536: ");
scanf("%d", &decimal);
if(decimal >= 65536) {
printf( "\n\nincorrect input!");
return EXIT_FAILURE;
}
number=decimal;
for(i=0; result!=0; i++){
result = number / 2; //change this line
rest = number %2; // change this line
number=result; // add this line
bits[i]=rest;
msb = i;
// return msb; //delete this line
}
printf("\n\n %d as binary number : ", decimal); // change this line
for(i=msb; i+1; i--){ // change the condition
// bits_2[msb-i+1] = bits[msb]; // delete this line
printf("%d", bits[i]); // change this line
}
return 0;
}
I noticed that you have a lot of useless variables so this is a compact version of your program:
#include <stdio.h>
#include <stdlib.h>
int main(void){
int i;
int bits[16];
unsigned int decimal;
int rest;
int result=1;
printf( "Input number smaller than 65536: ");
scanf("%d", &decimal);
if(decimal >= 65536) {
printf( "\n\nincorrect input!");
return EXIT_FAILURE;
}
else
printf("\n\n %d as binary number : ", decimal);
for(i=0; result!=0; i++){
result = decimal / 2;
rest = decimal %2;
decimal=result;
bits[i]=rest;
}
i--;
for(; i+1; i--){
printf("%d", bits[i]);
}
return 0;
}
I need a method to print a long with leading zeros in the form 123,456 with a comma between 3rd and 4th digit. I have this code for now:
#include <stdio.h>
void printWithComma (long num);
int main (void)
{
long number;
printf ("\nEnter a number with up to 6 digits: ");
scanf ("%ld", &number);
printWithComma (number);
return 0;
}
void printWithComma (long num)
{
//method to print the 6 digit number separated by comma
}
Example Output
Run 1
Enter a number with up to 6 digits: 123456
The number you entered is 123,456
Run 2
Enter a number with up to 6 digits: 12
The number you entered is 000,012
#include <stdio.h>
void printWithComma (long num);
int main()
{
long number;
printf("\nEnter a number with up to 6 digits: ");
scanf ("%ld", &number);
printWithComma(number);
return 0;
}
void printWithComma (long num)
{
int i, divisor, x;
char s[8];
divisor = 100000;
for(i = 0; i < 7; i++ ){
if( i == 3){
s[i] = ',';
continue;
}
if(divisor == 1){
s[i] = num % 10 + '0';
break;
}
x = num / divisor;
num %= divisor;
s[i] = x + '0';
divisor = divisor / 10;
}
s[7] = '\0';
printf("\n%s\n", s);
}
void printWithComma (long num) {
//method to print the 6 digit number separated by comma
char n[] = "000,000";
char *p[6] = { n+6, n+5, n+4, n+2, n+1, n };
int i;
for(i=0;num && i<6;++i, num/=10){
*p[i] += num % 10;
}
printf("\nThe number you entered is %s\n", n);
}
I've written a program that asks the user to input a number using strings, the program then will convert that number to decimal, however Im having a problem with it, when I compile (using -lm) and run the a.out, I get a Segmentation fault (core dumped), not really sure where to look or how to fix it, also one more question what do i need so that it prints the result of the conversion (printf("something..")) ?
#include <stdio.h>
#include <string.h>
#include <math.h>
int main()
{
char string[100];
int s;
char a;
char j;
int sum;
printf("B = B to D\n");
printf("D = D to B\n");
printf("choose which one to convert to:");
scanf("%c%c", &a, &j);
if (a == 'B')
{
printf("enter binary number to convert to decimal: ");
scanf("%s", string);
for(s = strlen-1; s >= 0; s--)
{
if(string[s] == '1')
{
sum = sum + pow(2,s);
}
}
}
return 0;
You probably meant to have strlen(string) - 1, not strlen - 1. My best guess is that your program is interpreting strlen as a function pointer, and it's pretty much a given that crazy things happen after that.
As it is, you might be interested in the strtol function, which appears to do exactly what you're looking for.
You use strlen as an integer. I think you mean strlen(string)
for(sum=0, j=0, s=strlen(string)-1; s >= 0; s--, ++j){
if(string[s] == '1'){
sum = sum + pow(2,j);
}
}
printf("%d\n",sum);
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
#include <stdlib.h>
void reverse_string(char *string)
{
int string_length = strlen(string);
char temp;
int i;
for (i = 0; i < string_length/2; i++)
{
temp = string[i];
string[i] = string[string_length - (i + 1)];
string[string_length - (i + 1)] = temp;
}
}
int main()
{
char string[100];
int s;
char a;
char j;
int sum = 0;
int string_length = 0;
int number, original_number;
int remainder;
char binary_string[200];
int i = 0;
printf("B = B to D\n");
printf("D = D to B\n");
printf("choose which one to convert to:");
scanf("%c%c", &a, &j);
a = toupper(a);
if (a == 'B')
{
printf("enter binary number to convert to decimal: ");
scanf("%s", string);
string_length = strlen(string);
for(s = strlen(string)-1; s >= 0; s--)
{
if(string[s] == '1')
{
sum = sum + pow(2,string_length - (s + 1));
}
}
printf("%s in binary is %d\n",string,sum);
}
else if (a == 'D')
{
printf("enter positive decimal number to convert to binary: ");
scanf("%s",string);
number = atoi(string);
original_number = number;
if ( number < 0 )
{
printf("ERROR: only positive numbers please\n");
return 1;
}
do
{
remainder = number % 2;
if ( remainder == 0 )
binary_string[i] = '0';
else
binary_string[i] = '1';
number = number / 2;
i += 1;
}
while (number > 0);
binary_string[i] = '\0';
reverse_string(binary_string);
printf("decimal %d is %s in binary\n",original_number,binary_string);
}
return 0;
}
strlen isn't used properly. I think you want to do something like strlen(string)-1. BTW your logic wont work to convert the fractional part. Check this code:
#include <stdio.h>
#define MAX 1000
int main()
{
double fraDecimal=0.0,dFractional=0.0 ,fraFactor=0.5;
long dIntegral = 0,bIntegral=0,bFractional[MAX];
long intFactor=1,remainder,i=0,k=0,flag=0;
char fraBinary[MAX];
printf("Enter any fractional binary number: ");
scanf("%s",&fraBinary);
while(fraBinary[i]) //Separating the integral and fractional parts
{
if(fraBinary[i] == '.')
flag = 1; //If dot is found start taking the fractional part.
else if(flag==0)
bIntegral = bIntegral * 10 + (fraBinary[i] -48);
/* char - 48 to get the numerical value.*/
else
bFractional[k++] = fraBinary[i] -48;
i++;
}
while(bIntegral!=0){
remainder=bIntegral%10;
dIntegral= dIntegral+remainder*intFactor;
intFactor=intFactor*2;
bIntegral=bIntegral/10;
}
for(i=0;i<k;i++){
dFractional = dFractional + bFractional[i] * fraFactor;
fraFactor = fraFactor / 2;
}
fraDecimal = dIntegral + dFractional ;
printf("Equivalent decimal value: %Lf",fraDecimal);
return 0;
}
Source:
C Program to Convert Binary into Decimal Number