Decimal to Binary in C, result printed all mismatched
Solved
C++ Gurus
-
I made a code in c that switches decimal to binary and vice versa, the issue I have is that when I do the convertion from decimal to binary it prints the numbers all mixed up, model, assuming I input the number 123 as a decimal it ought to print 11110110 however my program changes over it as 10111110
{Code}
#include <stdio.h> #include <stdlib.h> main() { int i, no, coc, re, opt; int dec; int bin, p, c; printf ("\n1. Decimal to binary \n2. binary to decimal \n choose an option: "); scanf("%d", &opt); switch(opt) { case 1: printf("\nDecimal No.: "); scanf("%d",&no); if (no>2) { printf("Your binary No.: "); for (i=1;1<=no; i++) { coc=no/2; no=coc; re=coc%2; printf("%d", re); } } break; case 2: printf("\nBinary No.: "); scanf("%d",&bin); c=1; dec=0; while(bin>0) { p=0; p=c*(bin%10); dec+=p; c*=2; bin/=10; } printf("Your decimal No.: %d",dec); break; default: printf("\a\n\nError"); break; } return 0; }
Here is the article I was reading before trying this all stuff https://www.scaler.com/topics/decimal-to-binary-in-c/
Thanks in advance!
-
Hi,
Your not doing the operations in the correct order and as the scaler various demonstration does, you are printing your result in the wrong order.