Adding Elements of Array

Hey Guys,
I have made a simple program to add the elements of any arry using a for loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream.h>

int main()
{
    int x, i;
    cin >> x;
    int Num[x];
    int Total = 0;
    for(i = 0; i < x; i++)
    {
          cin >> Num[i];
    }
    
    for(i = 0; i < x; i++)
    {
          Total = Total + Num[i];

    }
              cout << Total;

    cin.ignore();
    return 0;
}
You didn't ask a question so I guessing here.
First the size of an array should be defined at compile time:
int Num[x];, here x should be known. That is should be const.

The above code won't compile. If you want the above code can be implemented without storing the values. (i.e. use the values as being read to calculate the sum). If on the other hand need an array of undefined length in compile time (you need to find out in run time) use a different strategy like getting and array on heap.

But anyway you should probably just use vector<int> instead of array and be done with it.
My code was compiling, but when I ran it, after enterng all the array values, it wasn't printing any result.
I have also tried this code using Num[6], and faced the same problem there.
Topic archived. No new replies allowed.