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.
#include <iostream>
constint 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;
}