-
Help finding the error
I am trying to create the code for a program using a for loop that will add the elements of an array and display "sum = (sum of the array)". I think I am pretty close but I am getting 1 error. Can anyone give me a nudge in the right direction?
Code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int myarray[] = {3,5,22,4,17,6,14};
for (int i = 0; i < 7; i++)
{
sum += myarray[i];
}
cout << "sum = " << sum;
cout << endl;
return 0;
}
-
It looks like you forgot to declare sum and initialise it to 0.
-
You didn't create the variable sum.
Also, do indent properly.
And, don't put a row between each line. It only makes it harder to read.
-
Ok. Here's where I am at now. I've been struggling with this for 2 days now. Can somebody please tell me what I'm doing wrong?
Code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
int sum = 0
{
int myarray[] = {3,5,22,4,17,6,14};
for (int i = 0; i < 7; i++)
{
sum += myarray[i];
}
cout << "sum = " << sum;
cout << endl;
return 0;
}
Thanks!!!
-
sum must be defined inside the body of main...
-
Your placement of the definition of sum is incorrect. You probably intended to write:
Code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int sum = 0;
int myarray[] = {3,5,22,4,17,6,14};
for (int i = 0; i < 7; i++)
{
sum += myarray[i];
}
cout << "sum = " << sum << endl;
return 0;
}
-
Ok that worked. Thank you so much! I would have spent all weekend pulling my hair out over this!