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 :
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;
}