Home > Mobile >  Adding values in an array by skipping one specific value in every iteration
Adding values in an array by skipping one specific value in every iteration

Time:09-28

I am trying to solve this problem from hours but could not find a solution. What I am trying to do is, I have an array of 4 indexes arr[4] = {7, 3, 2, 4}. Now the task is to add every element in every iteration but skipping that value on which iteration is going on. For example:

input = arr[4] = {7, 3, 2, 4}

1st iteration : 3 2 4 = 9

2nd iteration : 7 2 4 = 13

3rd iteration : 7 3 4 = 14

4th iteration : 7 3 2 = 12

output = 9, 13, 14, 12.

This is what I have tried:

#include <iostream>

int main() {
    int arr[4] = {7, 3, 2, 4};
    int n = 4;
    int result = 0;
    int sum = 0;
    for(int i = 0; i < n; i  ){
        for (int j = 0; j < n; j  )
            sum  = arr[j]; 
            
        result = sum - arr[i];
        std::cout << result<< ',';
    }
    

    return 0;
}

Actual Output 9,29,46,60,

Expected Output 9, 13, 14, 12

CodePudding user response:

You have to move your sum declaration inside the outer for loop, so that it gets reset at every outer iteration. Then in every inner iteration, you only add the element, if i!=j. Then you don't need to subtract anything from sum and you don't need the additional result variable.

#include <iostream>

int main() {
    int arr[4] = {7, 3, 2, 4};
    int n = 4;
    int result = 0;
    for(int i = 0; i < n; i  ){
        int sum = 0;
        for (int j = 0; j < n; j  )
            if (i != j)
                sum  = arr[j]; 
            
        std::cout << sum<< ',';
    }
    

    return 0;
}

https://godbolt.org/z/7c9fG9j6K

Functional approach using C 20

I highly suggest to use a more functional approach to programming as opposed to your procedural code.

Two nested for-loops and managing two indices is error-prone and the code is hard to read.

Consider the following C 20 code:

#include <numeric> // for accumulate
#include <ranges>
#include <iostream>

int main() {
    int arr[4] = {7, 3, 2, 4};
    
    // calculate the sum of all elements
    auto sum = std::accumulate(std::begin(arr), std::end(arr), 0.0);

    // create a function (lambda) that subtracts sum from a double value
    auto subtract_from_sum = [sum](double const& value){
        return sum - value;
    };

    // transform the input array, by applying the minus_sum function to every
    // element
    auto res = arr | std::views::transform(subtract_from_sum);

    // print the result
    for (auto v: res) std::cout << v << " "; 
    return 0;
}

https://godbolt.org/z/8P8eW7vf8

The code is not necessarily shorter, but instead of telling the computer the steps it has to perform, you tell the computer the result that you want to have. Let me walk you through the code:

  1. You use std::accumulate to sum all elements of your array.
  2. You define a lambda expression (basically a function) subtract_from_sum, that subtracts a double value from sum.
  3. std::views::transform lets you create a new array, where every element is transformed by a function. Here you use the "pipe operator" | to pipe the input array arr to std::views::transform, which takes the previously defined lambda as the function that is to be applied to every element.
  4. You output the result.

All the ugly implementation details and for-loops are hidden away. It also has the additional benefit of being faster: With your approach, you sum n-1 values n times, so that you have n*(n-1) floating point operations. With this approach you sum n values and then perform n subtractions. So you have 2*n floating point operations in total.

Functional approach using C 11/C 14/C 17

In older C standards, you can also use a functional approach, but the code is a bit more verbose without the ranges capability of C 20

#include <numeric> // for accumulate
#include <vector>
#include <algorithm>
#include <iostream>

int main() {
    int arr[4] = {7, 3, 2, 4};
    
    // calculate the sum of all elements
    auto sum = std::accumulate(std::begin(arr), std::end(arr), 0.0);

    // create a function that subtracts sum from a double value
    auto subtract_from_sum = [sum](double const& value){
        return sum - value;
    };

    // transform the input array, by applying the subtract_from_sum function to every
    // element
    std::vector<double> res;
    std::transform(
        std::begin(arr),
        std::end(arr),
        std::back_inserter(res),
        subtract_from_sum
    );

    // print the result
    for (auto v: res) std::cout << v << " "; 
    return 0;
}

https://godbolt.org/z/avvxdnWEe

  • Related