- 2074 Chaitra · 6 marks
Decimal to binary conversion
Short answer
Divide the decimal number repeatedly by 2, storing remainders in an array; then print remainders in reverse order. For 0, output 0.
Write a program to convert a decimal number into binary number.
Method: divide the number repeatedly by 2 and store the remainders; the binary number is the remainders read in reverse order (last remainder first).
Example, 45: 45/2 = 22 r 1; 22/2 = 11 r 0; 11/2 = 5 r 1; 5/2 = 2 r 1; 2/2 = 1 r 0; 1/2 = 0 r 1. Reading upwards gives 101101.
#include <stdio.h>
int main(void)
{
int n, i = 0, j, bin[32];
printf("Enter a decimal number: ");
scanf("%d", &n);
if (n == 0)
bin[i++] = 0;
while (n > 0)
{
bin[i++] = n % 2; /* remainder is the next bit (LSB first) */
n = n / 2;
}
printf("Binary = ");
for (j = i - 1; j >= 0; j--)
printf("%d", bin[j]);
printf("\n");
return 0;
}
Output for 45:
Enter a decimal number: Binary = 101101
The remainders are stored in the array bin[] and printed from the last index down to 0.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Binary to decimal in FORTRAN · Computer Programming, chapter 11
- Correct program: Celsius to Fahrenheit · Computer Programming, chapter 3
- Employee text file; sort into binary file · Computer Programming, chapter 10
- Binary file of 48 students; highest mark · Computer Programming, chapter 10
- Convert date from BS to AD · Computer Programming, chapter 8 · asked 2×
- Convert case based on first character · Computer Programming, chapter 7
- Convert 37.432 decimal to binary · Digital Logic, chapter 1
- Convert octal 623.77 to decimal, binary, hex · Digital Logic, chapter 1
- 8085 ALP: BCD to binary conversion · Microprocessor, chapter 2
- Number conversions 33 to binary etc. · Basic Electronics Engineering, chapter 6