Search code examples
c++arraysarray-sum

Why is this not printing the final output of sum?


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


Solution

  • 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