Fix my sum array program?

Just trying to make a simple program that adds the numbers inputted. Not sure how to set it so you dont have to have a set amount of numbers such as "2" in mine. And it doesn't seem to run right. I get "85" for my output everytime. Any help? I can tell somethings missing but I dont know what.

code
#include <iostream>
using namespace std;

int main ()
{
 int numbers;
 cout << "Please enter ten numbers: " << endl;
 cin >> numbers;
 
 const int numb = 2;
 int values[numb];
 double total = 0;
 for (int i = 0; i < numb; i++)
 {
     total = total + values[i];
 }
 cout << total << endl;
 system ("pause");
 return 0;
}
First, you enter numbers but you don't actually use it anywhere in the code. Next, you only call cin>> once, but you need 10 numbers. You need to stick that in a loop.

Next, values[] is not initialized to anything so the output could be ANYTHING.

Since you have hard coded "ten numbers", I suggest you just set numb to 10 like so:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

int main ()
{
 cout << "Please enter ten numbers: " << endl;
 
 const int numb = 10;
 int values[numb];
 double total = 0;

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

 for (int i = 0; i < numb; i++)
 {
     total = total + values[i];
 }
 cout << total << endl;
 system ("pause");
 return 0;
}


If you want to make the number of inputs variable, maybe skip the array and do something like this which is much simpler:
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>
using namespace std;

int main ()
{
 int numb;
 double total = 0;

 cout << "How many numbers do you want? ";
 cin  >> numb;

 cout << "Please enter ten numbers: " << endl;
 
 for (int i = 0; i < numb; i++)
 {
  int input;
  cin >> input;
  total = total + input;
 }
 cout << total << endl;
 system ("pause");
 return 0;
}
Last edited on
You have uninitialised data in the array.
You could set it to zero like this
1
2
    const int numb = 2;
    int values[numb] = {0,0};

And your output will no longer be unpredictable. But it will always be zero.
If you just want to add some numbers, you don't need an array at all:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

int main()
{
    double total = 0;
    double numbers;
    cout << "Please enter some numbers: " << endl;
    cout << " (enter a letter to finish) " << endl;

    do {
        cin >> numbers;
        if (cin.good())
            total += numbers;

    } while(cin.good());

    cout << "Total = " << total << endl;

    return 0;
}
Topic archived. No new replies allowed.