help!!multiplication code+carry digits

Write here if you have problems with your C source code

Moderator: Board moderators

Post Reply
philae
New poster
Posts: 3
Joined: Sun Mar 05, 2006 1:53 pm

help!!multiplication code+carry digits

Post by philae »

hi!!My question is:I have two char arrays a and b[j] and their characters are numbers for example: a[] = "1653425", b [] = "436743"
so I wrote a code for multiplying numbers a =12 and b =18

Code: Select all

#include <stdio.h>
#include <string.h>

char x[] = "0012";
char y[] = "0018";
char z[7];
char r[7];

int main(void)
{
 int i, j;
 int temp;

 memset(z, '0', 8);
 memset(r, '0', 8);

 for(j = 3; j >= 0; j--)
 for(i = 3; i >= 0; i--)
{
 temp = (x[i] - '0') * (y[j] - '0') + (r[i+j+1] - '0');

 z[i+j+1] += (temp % 10);

 r[i+j] += (temp / 10);
}

and I cannot see what is wrong with it as it gives the incorrect result.
chunyi81
A great helper
Posts: 293
Joined: Sat Jun 21, 2003 4:19 am
Location: Singapore

Post by chunyi81 »

You declared r as char r[7] but in the nested for loops in your code you access r[i + j + 1] with i and j both starting at 3. This gives 3 + 3 + 1 = 7 and r[7] being accessed, which of course will read garbage and in this judge it will give a segmentation fault. Since you declared r as an array of 7 characters, you can only access r[0] to r[6] and not r[7].
philae
New poster
Posts: 3
Joined: Sun Mar 05, 2006 1:53 pm

Post by philae »

that's very careless of me..thank you, but there are still problems with carry digits:for example this code gives 18*12= 1;6
Darko
Guru
Posts: 580
Joined: Fri Nov 11, 2005 9:34 am
Location: Calgary, Canada

Post by Darko »

Ok, I am not sure what is going on here. I don't understand this conversion char-int that is taking place, so it's ugly, but seems to work:

Code: Select all

#include <stdio.h> 
#include <string.h> 

char x[] = "0012"; 
char y[] = "0018"; 
char z[8]; 
char r[8]; 

int main(void){ 
    int i, j, k; 
    int temp; 

    memset(z, '0', 8); 
    memset(r, '0', 8);
    
    for(j = 3; j >= 0; j--) {
        for(i = 3; i >= 0; i--){ 
        temp = (x[i] - '0') * (y[j] - '0') + (r[i+j+1]-'0'); 

        z[i+j+1] += (temp % 10);
        if(z[i+j+1]>'9'){
            z[i+j] += (z[i+j+1]-'0')/10;
            z[i+j+1] = (z[i+j+1]-'0')%10 + '0';
        }
        r[i+j] += (temp / 10);
        r[i+j+1] = '0';
        }
    }
    for(k=0;k<8;k++) printf("%c",z[k]);
    printf("\n");
    return 0;
}
Basically, you didn't take care of the case when digit becomes >9 and once you used a reminder you kept it around. I think that is it? And I am not sure why all those chars, why not just use ints? But, again, I don't know C much.

Darko
philae
New poster
Posts: 3
Joined: Sun Mar 05, 2006 1:53 pm

Post by philae »

thank you very much..... :lol: :lol: :lol: :lol:
Post Reply

Return to “C”