The error is in your use of sizeof()
. It returns the total size of what is passed in. You passed in an array of 5 integers. An int
is typically 4 bytes, so your sizeof()
should return 20.
The bare minimum fix is to change your for loop Boolean Expression:
i < sizeof(prime)
becomes i < sizeof(prime) / sizeof(*prime)
It takes the total size of your array (20) and divides it by the size of the first element (*prime) to give you the number of elements in your array.
To explain a bit more about *prime
, you need to understand that C-arrays decay to pointers to the first element if you look at them funny. The syntax here de-references the pointer and gives us the actual first element, an int
. And so we get the size of an int.
All the stuff below is tangential to your actual question, but I like to put it out there.
Here's your code, squashing your array initialization and using a range-based for loop.
#include <iostream>
int main()
{
int prime[]{2, 3, 5, 7, 11}; // CHANGED: Declare and initialize
int holder = 0;
// CHANGED: Range-based for loop
for (auto i : prime) {
holder += i; // CHANGED: in a range-based for loop, i is the value of each
// element
}
std::cout << "The sum of the 5 prime numbers in the array is " << holder
<< std::endl;
}
The range-based for loop works here because the array is in the same scope as the array. If you were passing the C-array to a function, it wouldn't work.
Here's your code using a Standard Library function:
#include <iostream>
#include <iterator> // std::begin and std::end because C-array
#include <numeric> // std::reduce OR std::accumulate
int main() {
int prime[]{2, 3, 5, 7, 11};
std::cout << "The sum of the 5 prime numbers in the array is "
<< std::reduce(std::begin(prime), std::end(prime)) << std::endl;
}
The need for <iterator>
is due to the fact that you are using a C-array. If we instead use a std::array
or [better yet] std::vector
, we can lose that requirement.
#include <iostream>
#include <numeric> // std::reduce
#include <vector>
int main() {
std::vector<int> prime{2, 3, 5, 7, 11};
std::cout << "The sum of the 5 prime numbers in the array is "
<< std::reduce(prime.begin(), prime.end()) << std::endl;
}
We got rid of the #include <iterator>
requirement because std::array
s and std::vector
s come with their own iterators. I also got rid of the holder
variable completely, as there was no demonstrated need to actually store the value; so we print it directly.
NOTES: std::reduce()
requires C++17, which any fairly recent compiler should provide. You could also use std::accumulate()
if you wish.
You can specify that you're compiling C++17 code by passing -std=c++17
to the compiler. It's always a good idea to specify what C++ standard you expect your code to run against. And while we're talking about compiler flags, it's in your best interest to enable warnings with -Wall -Wextra
at a minimum.