
Hi Isabella,
You’re absolutely right — range-based for loops are a great way to simplify your code. But in your case, the reason it doesn’t work likely has to do with how arrays behave when passed to functions in C++.
Here's the issue:
When you pass an array like this:
void find_average(double elements[5]) { ... }
Inside the function, elements is actually treated as a pointer (double*), not a real array. The compiler loses the size information, which the range-based for loop depends on to work.
So this:
for (double number : elements)
won’t work because C++ doesn’t know how many elements to loop over.
✅ How to fix it
Option 1: Use a loop with an explicit size
void find_average(double* elements, int size) {
double sum = 0.0;
for (int i = 0; i < size; ++i) {
sum += elements[i];
}
}
Option 2: Use std::array or std::vector
These keep size information, so range-based loops work fine:
#include
void find_average(const std::array& elements) {
double sum = 0.0;
for (double number : elements) {
sum += number;
}
}
So yes — range-based for loops do the same thing, but they only work when the size of the container is known. With plain arrays in functions, that size gets lost.
If you have more questions, I am here to help.
Our Experts
Sudip BhandariHead of Growth/Marketing
Apekchhya ShresthaSenior Product Manager
Kelish RaiTechnical Content Writer
Abhilekh GautamSystem Engineer
Palistha SinghTechnical Content Writer
Sarthak BaralSenior Content Editor
Saujanya Poudel
Abhay Jajodia
Nisha SharmaTechnical Content Writer
Udayan ShakyaTechnical Content Writer