357mag 3 Posted Saturday at 04:20 AM I've never used range-based for loops so I don't know how to write one that is keeping track of the sum of the elements in an array: int main() { int myArray[] = {2, 4, 7, 8, 9}; cout << "The values in the array are: "; for(int n : myArray) cout << n << " "; int sum = 0; for(int x : myArray) { x += myArray[x]; // don't know what to write here } cout << "The sum is: " << x << endl; // use of undeclared identifier system("pause"); return 0; } Share this post Link to post
Lajos Juhász 299 Posted Saturday at 04:24 AM It was a couple a decade ago when I wrote my previous C code. At that moment x is out of scope You should use sum to hold the result: sum +=myArray[x] cout << "The sum is: " << sum << endl; Share this post Link to post
357mag 3 Posted Saturday at 05:56 AM Something is still off. My console window is saying that sum is equal to 1985788. Share this post Link to post
Remy Lebeau 1442 Posted Saturday at 11:20 PM I find it interesting that you clearly knew how to access the element values in the 1st range-for loop, but didn't know how to do the exact same thing in the 2nd range-for loop. 1 Share this post Link to post