New to arrays & stuff, basic so help is appreciated!

Exercise 5.1.3. Write a program that prompts the user for each of seven values,
stores these in an array, and then prints out each of them, followed by the total.
You will need to write two for loops for this program: one for collecting data and
another for calculating the sum and printing out values.

I don't understand how to do this exercise using two for loops. This is the closest I've got and I receive an error when compiling (unqualified ID)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;
int main()
{
double scores[7];
cout << "Enter value #1" << endl;
cin >> scores[0];;
cout << "Enter value #2" << endl;
cin >> scores[1];
cout << "Enter value #3" << endl;
cin >> scores[2];
cout << "Enter value #4" << endl;
cin >> scores[3];
cout << "Enter value #5" << endl;
cin >> scores[4];
cout << "Enter value #6" << endl;
cin >> scores[5];
}
{
for (int i = 7; i < 7; i + scores[i];
cout << "The total of these integers is" << scores[i] endl;
system("PAUSE");
}


Help is appreciated. And does anyone know any good books that have lots of exercises? I tried C++ Primer Plus 5th edition, got to nearly page 200 and stopped because it was all text, little to no example and had lots of garbage junk that are pointless. I mean, they put the exercises at the END of the chapter, not as you learn new stuff.
The loop for collecting data would eliminate the need for all of those cin/cout statements:

1
2
3
4
5
for (int i = 0; i < 7; i++)
{
   cout << "Enter value #" << i+1 << endl;
   cin >> scores[i];
}



The loop for calculating and output would look like this:

1
2
3
4
5
6
7
8
9
10
double total = 0;

for (int j=0; j<7; j++)
{
   cout << "Value #" << j+1 << " is " << scores[j] << ". Adding to total" << endl;
   total += scores[j];
   cout << "Current total is " << total << endl;
}

cout << "Final total is " << total << endl;


Hope that helps.

EDIT: As general programming practice, might I suggest defining a constant for the max array amount? Something like:

1
2
3
4
5
6
7
8
9
10
const int MAX_ARRAY = 7;

double scores[MAX_ARRAY]; // This would then be the array declaration

// And in loops, you'd use it like this

for (int i=0; i < MAX_ARRAY; i++)
{
   . . .
}


Doing so means that if you ever need to change the size of that array, you just alter the constant, rather than every literal value of '7' in the code.

EDIT 2: The reason your code crashes is this:

for (int i = 7; i < 7; i + scores[i];

You're missing the closing brace. Even then, it's not going to do what you want because the increasing section of the loop is screwed.

Also, for your cout statement at the end, you indicate that it's a total of integers but you have an array of the other. In the interest of clarity, you should probably change one or the other.
Last edited on
Topic archived. No new replies allowed.