Decimal to Binary Display
C
Hard
4 views
Problem Description
Take a decimal number from the user (validation: positive integer only). Then convert it to binary and print it, also showing the step-by-step conversion process.
Official Solution
#include <stdio.h>
int main() {
int num, temp;
int binary[32];
int i = 0;
/* ---- Input & Validation ---- */
while (1) {
printf("Enter a positive integer: ");
if (scanf("%d", &num) != 1) {
printf("Invalid input! Please enter an integer.n");
while (getchar() != 'n'); // clear buffer
continue;
}
if (num <= 0) {
printf("Invalid input! Enter a positive integer only.n");
} else {
break;
}
}
/* ---- Conversion Process ---- */
temp = num;
printf("nStep-by-step conversion (Decimal to Binary):n");
printf("QuotienttRemaindern");
while (temp > 0) {
binary[i] = temp % 2;
printf("%dtt%dn", temp / 2, binary[i]);
temp = temp / 2;
i++;
}
/* ---- Print Binary ---- */
printf("nBinary equivalent of %d is: ", num);
for (int j = i - 1; j >= 0; j--) {
printf("%d", binary[j]);
}
printf("n");
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!