-
another array exercise
Hi.. I have another array exercise and it has this debug error again but this time it doesn't give the sum output.
The code is as follows:
Code:
//array initialization and sum output based on user input
#include <iostream>
using namespace std;
int main ()
{
int ar[7] = {ar[0], ar[1], ar[2], ar[3], ar[4], ar[5], ar[6]};
int sumArray = 0;
int i = 0;
cout << "Enter an integer for value 1: ";
cin >> ar[0];
cout << "Enter an integer for value 2: ";
cin >> ar[1];
cout << "Enter an integer for value 3: ";
cin >> ar[2];
cout << "Enter an integer for value 4: ";
cin >> ar[3];
cout << "Enter an integer for value 5: ";
cin >> ar[4];
cout << "Enter an integer for value 6: ";
cin >> ar[5];
cout << "Enter an integer for value 7: ";
cin >> ar[6];
for (i = 0; i < 7; i++);
{
sumArray += ar[i];
}
cout << endl;
cout << "Total is: ";
cout << sumArray << endl;
}
Any ideas will be great! Thanks..
-
Quote:
Code:
int ar[7] = {ar[0], ar[1], ar[2], ar[3], ar[4], ar[5], ar[6]};
In some languages, this doesn't even compile, and for good reason. Just what do you think this should achieve?
-
Code:
for (i = 0; i < 7; i++);
{
sumArray += ar[i];
}
The semicolon at the end of the for loop is wrong.
Try:
Code:
#include <iostream>
using namespace std;
int main ()
{
int ar[7];
int sumArray = 0;
int i;
for (i = 0; i < 7; i++)
{
cout << "Enter an integer for value " << i+1 << ": ";
cin >> ar[i];
sumArray += ar[i];
}
cout << endl << "Total is: " << sumArray << endl;
}
-
Or even, since you don't ever use the array:
Code:
#include <iostream>
using namespace std;
int main ()
{
int sum = 0;
for (int i = 0; i < 7; i++)
{
cout << "Enter an integer for value " << i+1 << ": ";
int tmp;
cin >> tmp;
sum += tmp;
}
cout << endl << "Total is: " << sum << endl;
}
-
Thanks CornedBee and hk for pointing out my mistakes..
It's working fine now.. I chose to stick with the array since it's an array exercise although CornedBee's program also works!
Code:
//array initialization and sum output based on user input
#include <iostream>
using namespace std;
int main ()
{
int ar[7];
int sumArray = 0;
int i = 0;
for (i = 0; i < 7; i++)
{
cout << "Enter an value for " << i + 1 << " : ";
cin >> ar[i];
sumArray += ar[i];
}
cout << endl;
cout << "Total is: ";
cout << sumArray << endl;
}
Again, thanks for the help, guys!!