In: Computer Science
6.19 LAB: Convert to binary - functions
Write a program that takes in a positive integer as input, and outputs a string of 1's and 0's representing the integer in binary. For an integer x, the algorithm is:
As long as x is greater than 0 Output x % 2 (remainder is either 0 or 1) x = x / 2
Note: The above algorithm outputs the 0's and 1's in reverse order. You will need to write a second function to reverse the string.
Ex: If the input is:
6
the output is:
110
Your program must define and call the following two functions. The IntegerToReverseBinary function should assign binaryValue with a string of 1's and 0's representing the integerValue in binary (in reverse order). The ReverseString function should assign reversedString with the reverse of inputString.
void IntegerToReverseBinary(int integerValue, char
binaryValue[])
void ReverseString(char inputString[], char reversedString[])
PRORGAM IN C
#include
#include
#include
// declare functions
void IntegerToReverseBinary(int integerValue, char
binaryValue[]);
void ReverseString(char inputString[], char
reversedString[]);
int main()
{
// variable and array declarations
int integerValue;
char binaryValue[20];
char reversedString[20];
int i;
printf("Enter integer: "); // print message
scanf("%d",&integerValue); // take input
IntegerToReverseBinary(integerValue,binaryValue); //
call func
ReverseString(binaryValue,reversedString); // call
func
printf("In Binary: "); // print message
for(i = 0; reversedString[i]!='\0'; i++){ // print
string
printf("%c",reversedString[i]);
}
}
void IntegerToReverseBinary(int integerValue, char
binaryValue[]){
int i = 0;
while (integerValue > 0) { // run till integervalue >0
// storing remainder in binary array
binaryValue[i] = (integerValue % 2)+'0'; // '0' convert int to
char
integerValue = integerValue / 2; //
decrease value
i++;
}
binaryValue[i] = '\0'; // set null to last index
}
void ReverseString(char inputString[], char
reversedString[]){
int len = strlen(inputString); // get len of input
string
int i = 0,j ; // variable declaration
for(j=len-1; j>=0; j--){ // reverse string
reversedString[i] =
inputString[j];
i++;
}
reversedString[i] = '\0'; // set null to last
character
}
/* OUTPUT */