Multiplying two arrays

I'm trying to multiply two arrays they are set up number{......0,0,0,0,1,2,3},number2 {.......0,0,0,0,0,1,2,3}, and ans[] is filled with zeros, but I get an error every time I know it has to do with something in the loops, but I'm not sure what.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void multiply(int number1[], int number2[], int ans[])
{
	int k;
	for (int j = 59; j >= 0; j--)
	{
		k = j;
		for (int i = 59; i >= 0; i--)
		{
			
			ans[k] = number1[k] * number2[k];
			ans[k - 1] = ans[k] / 10;
			ans[k] = ans[k] % 10;
			k--;
		}
	}
			
}
closed account (SECMoG1T)
Exactlly how are you trying to multiply your arrays?
Without seeing how ans[], number1[], and number2[] were defined I'll just guess that this line is the problem:

ans[k - 1] = ans[k] / 10;
When k is equal to zero you will access your ans[] array out of bounds.

Also is there a reason you're iterating through the array from the last element to the first element? And I really don't understand the purpose of that inner loop.

I am starting at the end because the numbers in the arrays are at the end. I'm setting it up to multiply as

number1 000123
x number2 000123
equals answer 015129

the code is actually
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void multiply(int number1[], int number2[], int ans[])
{
	int k;
	for (int j = 59; j >= 0; j--)
	{
		k = j;
		for (int i = 59; i >= 0; i--)
		{
			
			ans[k] = number1[i] * number2[j] + ans[k];
			ans[k - 1] = ans[k] / 10;//carry for num greater than 1 digit
			ans[k] = ans[k] % 10;//stores the ones place
			k--;
		}
	}
			
}

I had k's where i and j should have been and edited a few other mistakes. Sorry for the confusion. I realize that the k is going outside of the array bounds is there another way to write the loop to keep that from happening?
Last edited on
Topic archived. No new replies allowed.