The input for this program should be like this:

How many tests? 4
Grade on Test 1? 95
Grade on Test 2? 88
Grade on Test 3? 80
Grade on Test 4? 96
Your average is: 89.75 <------- this is where I can't get it right, can anybody take a look at my code and tell me how to get all those scores for average? Thanks.

Here is my code:

int main()
{
	int totnum[20] ;
	int c = 1 , x ;

	cout << "How many tests? " ;
	cin >> x ;

	while (c <= x)
	{
		cout << "Grade on Test " << c << "? " ;
		cin >> totnum[c]; c = c + 1;
	}

	double avg = totnum[20]/x;
	cout << "Your average is " << avg << endl ;
}

Recommended Answers

All 5 Replies

And array is just a contiguous block of memory. Its doesn't support the division operator.

I see. How exactly do I sum up all the scores for average?

totnum[20]/x; That line accesses an element of the array that doesn't exist, it's one past the end of the array because the array is size 20 and indices start at 0.

Also, when you use the subscript operator "[ ]" on the array, you're accessing only one element. You'll need to loop through each element of the array (up to the num. of test items) and add them together, then divide by the number of test items.

I see. How exactly do I sum up all the scores for average?

Try something like below...Note array elements start at zero not 1.

#include <iostream>

#define ARR_SIZE 5

int main()
{
  int totnum[ARR_SIZE];
  signed long sum = 0;
  
  for (size_t i = 0; i < ARR_SIZE; ++i)
  {
	std::cout << "Enter element [" << i << "]->";//note array elements start at 0
	std::cin >> totnum[i];
  }

  for (size_t i = 0; i < ARR_SIZE; ++i)
  {
	std::cout << "Element [" << i << "]->" << totnum[i] << std::endl;
	sum += totnum[i];
  }
  
  std::cout << "sum->" << sum << std::endl;
  return 0;
}

I got rid of "double avg = totnum[20]/x;" and added a for statement. Now it is working beautifully. Thank you, gerard4143 and pseudorandom21!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.