Not adding right

Sorry that this is my second post tonight. But I finally got this program working but its not adding correctly. Instead of 2 + 2 = 4 it equals 8.

The program is supposed to be able to take a list of up to 100 integers and output the sum.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <cmath>
using namespace std;
const int NUM = 100;

int main(){

	// init variable
	int sum = 0;

	// init array
	int arr[NUM];
	for (int i = 0; i < NUM; i++)
		arr[i] = 0;

	// Welcome and Prompt
	cout << "Welcome to the line adder\n"
		<< "Please enter the numbers you wish to be added" << endl;

	// getting the numbers into the array
	for ( int i = 0; i < NUM; i++){
		 if (cin.peek() != '\n'){
			 cin >> arr[i];
		 
			 for (int j = 0; j < arr[i]; j++){
				sum = sum + arr[i];	
			 }
		 }
		 else{
			break;
		 }
	}
	cout << sum;

		// pause and exit
		getchar();
		getchar();
		return 0;
}
Your problem is that you're double, triple, quadruple... counting becase of your for-loop on line 25. You only want to add the number last inputted to sum, but instead you loop through your whole arr again.
I thought it might have something to do with that. However, if i place that loop anywhere else arr[i] isn't identified. So i have no idea where to put it. Should i make another array and copy arrr[i] into it?
You do not need a loop. You only need to add a value to sum every time you get a value from the user. You only need the statement in the loop, not the actual loop surrounding it.
OH! That makes so much sense!
Both problems you helped me resolve were such a quick fix.
Thank you again!
Topic archived. No new replies allowed.