Jump to content
357mag

How do I use a range-based for loop to sum all elements

Recommended Posts

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

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

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. 

  • Confused 1

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×