Array sum noob problem

I'm working on a problem from the C++ primer plus (5th edition) book, more specifically, chapter - listing 7.5
The problem is that when I try to sum all the array elements it stops when it reaches the value 7. That means it stops because it's considering the value of the array element rather than the index, right?..
Instead of stopping at value 7, I want the program to actually sum each array element ( cookies[0] + cookies [1] ... cookies [7])
until it reaches the ArSize limit, not the vaule 8.

Probably I'm just overlooking something and I'm a fool. But I can't seem to pick up on what lol.
Sorry if my wording isn't the best and thanks in advance.


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>
const int ArSize = 8;
int sum_arr(int arr[], int n);
int main()
{
	int cookies[ArSize] = {1,2,4,8,16,32,64,128};
	
	int sum = sum_arr(cookies, ArSize);
	
	std::cout << "The sum of all cookies is: " << sum << "\n";
	
	return 0;	
}

int sum_arr(int arr[], int n)
{
	int i = 0;
	int total = 0;
	for (i = 0; arr[i] < n; i++){
		total += arr[i];
	}
	
	return total;
}
line 19
 
    for (i = 0; arr[i] < n; i++){

should be
 
    for (i = 0; i < n; i++){
End me. Thank you haha!
Not very related but...

You should put:
using namespace std;

at the very top of the code,this way you won't have to write :
std::cout
instead u can only write cout << "some statements";

Not very related but...

You should put:
using namespace std;

This is something which can be discussed at length. However there are good reasons why people prefer not to do that.
Topic archived. No new replies allowed.