Hundurinn Nero
Hundurinn Nero

Reputation: 83

Array Multiplication in c++

This is homework.

I am trying to multiply the a and b array together using this formula:

c[0]=a[0]*b[0]+a[0]*b[1]+a[0]*b[2]+....a[0]*b[n-1]

c[1]=a[1]*b[1]+a[1]*b[2]+a[1]*b[3]+....a[1]*b[n-1]

and so on...

But this code seems to only run through the a array but never through the b array. The results I get look this:

6
12
18
9
6
15

Any pointers would be greatly appreciated.

My code -

#include <iostream>

using namespace std;
const int n=6;
int main()
{

int a[n]= {2,4,6,3,2,5};
int b[n]= {3,2,1,4,2,3};
int c[n];

for (int h=0; h<n; h++)
{
    for (int g=0; g<n; g++)
    {
        c[h] = a[h]*b[g];
    }
}

for (int i=0; i<n; i++)
{
    cout << c[i] << endl;
}
}

Upvotes: 1

Views: 10943

Answers (4)

Lefteris E
Lefteris E

Reputation: 2814

You can simplify the problem by making A[i] the common factor

So you get

c[0]  =a[0]  *(b[0]+b[1]+b[2]+...+b[n-1])
c[1]  =a[1]  *(b[1]+b[2]+...+b[n-1])
c[n-1]=a[n-1]*(b[n-1])

So an O(n) solution would be:

int sumB = 0;        
for (int i=n-1; i >= 0; --i){
  sumB += b[i];
  c[i] = a[i] * sumB;
}

Upvotes: 2

Anshuman
Anshuman

Reputation: 587

Line 16 should be:

c[h] = c[h] + a[h] * b[g];

Rest of the code looks ok!

Upvotes: 0

J L
J L

Reputation: 367

are you trying to get each element in the c array to be the product of each same element in the a and b arrays? if so just use c[0] = a[0]*b[0], c[1] = a[1]*b[1], etc.

Upvotes: 0

Konrad Rudolph
Konrad Rudolph

Reputation: 545578

c[h] = a[h]*b[g];

This line is overriding the value of c[h] for every value of b so only the last value (a[n - 1] * b[n - 1]) is saved. You need to accumulate (add up) the values from iterating over b, and you need to initialise c[h] beforehand.

for (int g=0; g<n; g++)

This iterates over the whole b array but your pseudocode shows that you only want to iterate over h…n.

Here’s a (properly indented!) solution:

int main() {
    int a[n] = {2, 4, 6, 3, 2, 5};
    int b[n] = {3, 2, 1, 4, 2, 3};
    int c[n] = {0};

    for (int h = 0; h < n; ++h)
        for (int g = h; g < n; ++g)
            c[h] += a[h] * b[g];

    for (int i = 0; i < n; ++i)
        std::cout << c[i] << '\n';
}

Upvotes: 1

Related Questions