Why is this not printing the final output of sum?

402 Views Asked by At

Given an array of N integers. My task is to print the sum of all of the integers.

Input:

First line of input file contains a single integer T which denotes the number of test cases. For each test case, there will be two lines. First line contains N which denotes number of elements in an array, and second line contains N space seperated integers.

Output:

Corresponding to each test case, print the sum of array in a new line.

Constraints:

1 <= T <= 100

1 <= N <= 1000

0 <= Arr[i] <= 200

#include <iostream>
using namespace std;

int main()
{
    int n, no_of_elem_array;
    int arr[50], sum[50];

    cin >> n;

    int j = 0;

    while (n--) {
        cin >> no_of_elem_array;

        for (int i = 0; i < no_of_elem_array; i++) {
            cin >> arr[i];
        }

        for (int i = 0; i < no_of_elem_array; i++) {
            sum[j] = sum[j] + arr[i];
        }
        j++;
    }
    for (int i = 0; i < n; i++) {
        cout << sum[i] << endl;
    }

    return 0;
}

Output

2

4

1 2 3 4

6

5 8 3 10 22 45

3

There are 3 best solutions below

0
On BEST ANSWER

There is n in your final loop

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

which is become 0 in

         while(n--)

that is why it is not print anything

3
On

Two issues:

  1. Your arrays are not big enough, so there will be invalid access, which is undefined behaviour.

  2. Array sum is local variable, so the value is uninitialized (i.e. It contains arbitrary values when allocated), you need to set them to zero by yourself.

2
On

That is not how one adds arrays in C++:

This is the code I propose:

#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>

int main() {
    std::vector<int> vec_of_ints;
    std::cout << "Enter the size of the array: ";
    unsigned size = 0;
    std::cin >> size;
    vec_of_ints.resize(size);
    for(auto& integer : vec_of_ints) {
        std::cin >> integer;
    }
    std::cout << std::accumulate(vec_of_ints.begin(), vec_of_ints.end(), 0);
    return 0;
}

Also, as @Alan Birtles has suggested, there is another (and better) alternative:

you do not need to store the input at all:

int main() {
    unsigned size = 0;
    std::cin >> size;
    long sum = 0;
    for (int i = 0; i < size; i++) {
        int num = 0;
        std::cin >> num;
        sum += num;
    }
    std::cout << sum << "\n";
    return 0;
}