Dynamic Memory Allocation, Arrays, Pointers

Starr

Daemon Poster
Messages
926
Ok I have a question. I am using dynamic memory allocation to create an array thats size is determined by the user. Now, after the user designates the size of the array I want to add all of the values in the and divide by the size of the array. (the program is determinging the averages of grades).

Ok, what I tried is, I tried to create a for loop that said:

Code:
for (int i = 0; i < numTests; i++)
		sum += iPtr[i];

'i' is the array variable for the pointer and 'numTests' is the size of the array that the user determines.

The closest I got was I got one term of the array divided by the size of the array determined by the user.

I am new to programming so cut me some slack.

The language should be obvious, if it's not then you wouldn't know the answer.

If you want I can post the entire code.
 
Could you post your code? It'll make it easier to help you:)

**Is iPtr the name of the array you are using?**
 
Starr said:
Code:
for (int i = 0; i < numTests; i++)
		sum += iPtr[i];

'i' is the array variable for the pointer and 'numTests' is the size of the array that the user determines.

Don't use a pointer, just use the array name, whatever that is.
 
Yes, iPtr is the name of the pointer.

Code:
#include <iostream>
using namespace std; 
int main()
{
	int numTests;
	float sum, ans;
	cout << "Enter the number of grades that you need to find the average of: ";
	cin >> numTests;
	int * iPtr = new int[numTests];
	for (int i = 0; i < numTests; i++)
	{
		cout << "Enter test score #" << i + 1 << " : "; 
		cin >> iPtr[i]; 
	}
	for (int i = 0; i < numTests; i++)
	{
		sum = sum + iPtr[i];  
	}
	cout << "The sum of the test scores is: " << sum << endl;
	for (int i = 0; i < numTests; i++)
		ans = sum / numTests;
	cout << "The average of all of the grades is: " << ans << endl;
	delete [] iPtr;
	return 0;
}

There it is with the natest stuff I tried.
 
From the initial code snippet you supplied, it looked like Java to me..oh well. Why are you making the following for loop?
Code:
for (int i = 0; i < numTests; i++)
           ans = sum / numTests;

If you want the average, try the following:
Code:
ans = sum / numTests;

* I also forget, do variables have to be given a value (i.e 0 or null) before they can be used in C++? *
 
No, you don't have to assign them anything. You just have to declare them.
 
Kind of. But I figured it OUT!!!!!! You question helped me. About do you need to assign the variable to anything. Well in this case sum needed to be assigned to something because it is being used in a math problem. So it needed to be assigned to 0. So I thank you knight for asking your question.
 
Back
Top Bottom