Search code examples
c++arraysmultiplication

How can we multiply each elements of an array to each other and store each product values in a array in c++?


example: let's say we have an array of arr1 [1,2,3,4] , the products will be 1x2, 1x3, 1x4, 2x1, 2x3, 2x4, 3x1, 3x2, 3x4, 4x1, 4x, 4x3. so the new array will be like arr2 [2,3,4,2,6,8,3,6,12,4,8,12]. I thought about going with :

for( int i=0; i<n; i++){
    for(int j=0; j<n; j++){
       arr2[i]= arr1[j] * arr1[j+1];
    }
}

But that only multiplies consecutive elements and not all. Can someone tell me the logic/algorithm?


Solution

  • Use an if statement to check that i != j before doing the multiplication.

    You also need another index variable to hold the index in the output array, you can't use i for this, since it stops at n. You also can't use i*n + j because you're skipping elements (there may be a formula for the desired index, but using another variable is simpler).

    int k = 0;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (i != j) {
                arr2[k++] = arr1[i] * arr1[j];
            }
        }
    }