How to update array items by multiplying with other items in c++

Viewed 125

The result I want to get is Multiply the index value with other index value. e.g in the code below: i want to update arr[0] value by arr[0]*arr[1], arr[9] value by arr[9]*arr[9-8] and for remaining indexes it'll be arr[i-1] * arr[i] * arr[i+1]. It is working fine on first index but at other indexes I am getting unexpected result.

#include<iostream>
using namespace std;

int main(){
    int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, j, k;
    
    for(j = 0; j < 10; j++){
        if(j == 0){
            arr[j] = arr[j] * arr[j + 1];
        }else if(j == 9){
            arr[j] = arr[j] * arr[j - 1];
        }else{
            arr[j] = arr[j - 1] * arr[j] * arr[j + 1];
        }
    }
    
    for(k = 0; k < 10; k++){
        cout<<arr[k]<<" ";
    }
}

Output: 2 12 144 2880 86400 3628800 203212800 1746419712 -1736015872 -180289536

Expected Result: 2 6 24 60 120 210 336 504 720 90

1 Answers

You need to store the results in a separate array or else you overwrite the values in the same array you use for future calculations.

In your case, when j == 0 you do:

arr[0] = arr[0] * arr[1]; // 1 * 2 = 2

So arr[0] is now 2. You then do

arr[1] = arr[0] * arr[1] * arr[2]; // 2 * 2 * 3 = 12, not 1 * 2 * 3 = 6

...and so on. If you instead store the result in a separate array, that problem goes away. Example:

#include <iostream>
// using namespace std; // Don't use this.

int main(){
    int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int res[10] = {0};
    
    for(int j = 0; j < 10; j++) {
        if (j == 0)
            res[j] = arr[j] * arr[j + 1];
        else if (j == 9)
            res[j] = arr[j] * arr[j - 1];
        else
            res[j] = arr[j - 1] * arr[j] * arr[j + 1];
    }
    
    for(int k = 0; k < 10; k++)
        std::cout << res[k] << ' ';
}

Output:

2 6 24 60 120 210 336 504 720 90 
Related