Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Problem adding all the elements in an array using a ranged-based for loop

#include <iostream>
using namespace std;
int main() {  

    double numbers[] = {7, 5, 6, 12, 35, 27};
    double average, count, sum = 0;

    cout << "The numbers are: ";

    for(const double &n : numbers) {
        cout << n << " ";
    }

    cout << endl;

    cout << "The sum is: ";

    for(const double &n : numbers) {
        sum += n;
        cout << sum;
    }

    cout << endl;
    return 0;

}

The output of sum should be 92 for adding all the elements in the array and i don’t know where i went wrong but this what keeps appearing to me instead:

The sum is 71218306592

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Split this output

71218306592

like

7 12 18 30 65 92

using this statement in the last range-based for loop

cout << sum << ' ';

Or place this statement

cout << sum;

outside the last range-based for loop.

for(const double &n : numbers) {
    sum += n;
}
cout << sum;

Pay attention to that neither variable average nor count is used in your program.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading