I have written a program that accepts a decimal number as input and converts it to BCD representation. My code is unable to print the value of the output, feel free to point out the errors. Kindly find the code attached below:

Code:

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main()
{
int n,i=0,j=0,rem,bcd[100][100]={0};
/*n is the input number, rem stores the individual digits of the input number for conversion
bcd[100][100] is the array used for storing the converted values, with the first index storing
the number of digits and the second the value, for example if 14 is given as an input number,
bcd[0][0...3] stores 0100 and bcd[1][0...3] stores 0001*/
printf("Enter the number to be converted");
scanf("%d",&n);
while(n!=0)
{
rem=n%10;
n=n/10;
/*this loop converts the individual digits of the input decimal into bcd*/
while(rem!=0)
{
bcd[i][j]=rem%2;
rem=rem/2;
j+=1;
}
i+=1;
j=0;
}
printf("The BCD representation of the input number is");
for(;i>=0;i--)
{
for(;j>=0;j--)
{
printf("%d",bcd[i][j]);
}
}
system("pause");
return 0;
}

Thank you for your help.

04-13-2012

anduril462

Why is bcd 100x100 if you are only using 100x4? Just declare it bcd[100][4].

You need to initialize j in your for loop, otherwise, it's stuck at 0 after the first time.