In: Computer Science
Write a program that prompts the user to enter a positive integer and then computes the equivalent binary number and outputs it. The program should consist of 3 files.
dec2bin.c that has function dec2bin() implementation to return char array corresponding to binary number.
dec2bin.h header file that has function prototype for dec2bin() function
dec2binconv.c file with main function that calls dec2bin and print results.
This is what i have so far. Im doing this in unix. All the files compiled fine but when i tried to link them I got errors.
dec2bin.c
#include <stdio.h>
#include <string.h>
#include "dec2bin.h"
void dec2bin(int x, char s[])
{
int i,k;
char s1[8];
for(i=0; x > 0; i++)
{
if(x%2) s1[i] = '1';
else s1[i] = '0';
x = x/2;
}
//reverses the string s1 and store the result in s
k = strlen(s1);
for(i=0; s1[i] != ' \0' ; i++)
s[k-i] = s1[i];
}
dec2bin.h
#include <stdio.h>
#include <string.h>
void dec2bin(int x, char s[])
dec2binconv.c
#include <stdio.h>
#include <string.h>
#include "dec2bin.c"
#include "dec2bin.h"
int main()
{
int x;
char arr[8];
printf("Enter an integer\n");
scanf("%d", &x);
dec2bin(x,arr[8]);
printf("%s",arr);
return 0;
}
// dec2bin.h
#include <stdio.h>
#include <string.h>
void dec2bin(int x, char s[]);
-----------------------------------------------------------------------------------------------------------
// dec2bin.c
#include "dec2bin.h"
void dec2bin(int x, char s[])
{
int i=0,k=0;
char s1[8];
for(i=0; x > 0; i++)
{
if(x%2)
{
s1[i] = '1';
}
else
{
s1[i] = '0';
}
x = x/2;
}
k = strlen(s1);
for(i=0; s1[i] != '\0' ; i++)
{
s[k-i] = s1[i];
}
}
-------------------------------------------------------------------------------------------------------------
// dec2binconv.c
#include "dec2bin.h"
int main()
{
int x=0;
char arr[8];
printf("Enter an integer\n");
scanf("%d", &x);
dec2bin(x,arr);
printf("%s\n",arr);
return 0;
}
--------------------------------------------------------------------------------------------------------------------------------------------------------
command for run program on terminal
gcc dec2binconv.c dec2bin.c
./a.out
-----------------------------------------------------------------------------------