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

Certain element sum from array

new to C++ and in need of help with an array. Looking at the code below, you can see I have an array of 20 undefined elements. My queastion is how do I sum up elements from a[5] to a[14]. Only these elements. (Including them ofc)

#include <iostream>

using namespace std;

int main()
{
    
    int a[20];
    int summa;
    
    for (int i = 0; i < 20; i++) {
        a[i] = rand()%6 + 5;
        cout << a[i] << "\n";
    }
}

>Solution :

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

Use your knowledge of a for loop to add those values to your summa variable (which you did not initialize):

#include <iostream>

using namespace std;

int main()
{
    
    int a[20];
    // set this to 0 or your answer will be erroneous
    int summa = 0;
    
    for (int i = 0; i < 20; i++) {
        a[i] = rand()%6 + 5;
        cout << a[i] << " ";
    }
    cout << endl;

    // Now sum the values you want
    for (int i = 5; i < 15; i++) {
        summa += a[i];
    }
    cout << "Sum from 5 to 14: " << summa << endl;
}
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