In: Computer Science
Write a program in C that reads prompts the user for a positive integer and then prints out that number in base 16, base 8 and base 2.
Implement te program as follows:
Program:
#include <stdio.h>
int main()
{
int num; /* declare integer variable num to store a number */
int binaryNum[32]; /* array to store binary number */
int i = 0; /* counter for binary array */
printf("Enter a positive integer: "); /* ask the user to enter an integer */
scanf("%d", &num); /* read integer from user */
printf("\nBase 10 number : %d ", num); /* print base 10 number using %d format command */
printf("\nBase 8 number : %o", num); /* print base 8 number using %o format command */
printf("\nBase 16 number : %x", num); /* print base 16 number using %x format command */
/* convert num to binary */
while (num > 0) { /* repeat until num<0 */
binaryNum[i] = num % 2; /* storing remainder in binary array */
num = num / 2; /* divide num by 2 */
i++; /* increment i by 1 */
}
printf("\nBase 2 number : ");
for (int j = i - 1; j >= 0; j--) // printing binary array in reverse order
printf("%d",binaryNum[j]);
return 0;
}
Screenshot:

Output:

Please don't forget to give a Thumbs Up.