I am trying to multiply two numbers kept in two 1d arrays. After I kept them in a 2d array(like we do in standard multiplication), the output isn't what I am expecting. Here's how far I have done so far
int main()
{
int n, m, i, j;
printf("Enter multiplicand(n) size: ");
scanf("%d", &n);
printf("Enter multiplier(m) size: ");
scanf("%d", &m);
int a[n], b[m];
printf("Enter multiplicands: ");
for(i = 0; i<n; i++)
{
scanf("%d", &a[i]);
}
printf("Enter multipliers: ");
for(i = 0; i<m; i++)
{
scanf("%d", &b[i]);
}
int c[m][n+m];
int k = 0 , l = m+n-1 , p = 2;
int ans = 0, carry = 0;
for(i = 0; i<m; i++)
{
for(j = 0; j<m+n; j++)
{
c[i][j] = 0;
}
}
for(i = m-1; i>=0; i--)
{
for(j = n-1; j>=0; j--)
{
if(a[j]*b[i] < 10)
{
c[k][l] = a[j]*b[i];
l--;
}
else if(carry > 0 && a[j]*b[i] < 10)
{
ans = a[j]*b[i] + carry;
c[k][l] = ans;
carry--;
l--;
}
else if(carry > 0 && a[j]*b[i] > 10)
{
ans = a[j]*b[i]%10 + carry;
c[k][l] = ans;
l--;
}
else if(carry > 0 && a[j]*b[i] == 10)
{
ans = (a[j]*b[i])%10 + carry;
c[k][l] = ans;
carry++;
l--;
}
else
{
ans = a[j]*b[i]%10;
c[k][l] = ans;
carry++;
l--;
}
}
l = m+n-p;
p++;
k++;
carry = 0;
ans = 0;
}
for(i = 0; i<m; i++)
{
for(j = 0; j<m+n; j++)
{
printf("%d ", c[i][j]);
}
printf("\n");
}
}
If I multiply 594 with 232 I should get:
0 0 1 1 8 8
0 1 7 8 2 0
1 1 8 8 0 0
but the program is returning:
0 0 0 1 8 8
0 0 6 8 2 0
0 1 8 8 0 0