View Single Post
Old Jul 2nd, 2007, 7:25 PM   #1
357mag
Hobbyist Programmer
 
Join Date: Mar 2005
Posts: 148
Rep Power: 4 357mag is on a distinguished road
Getting the wrong answer

I've got this program that uses the new operator with an array. I'm studying pointers and I read that you can use the new operator with an array and a pointer if you don't know how big the array is going to be. So I wrote this program that asks the user how many elements he would like in his array. Then he inputs that. Next, it asks him to enter the values for the elements. Then it inputs that. Finally, I want the program to simply output the sum of the elements. But I'm getting the wrong answer for the sum. I'm just kind of doing this by myself, my books don't show examples similar to this so here is my program:

int main()
{
	int max = 0;
	int sum = 0;
	int count = 0;
	
	cout << "Enter the number of elements you would like: ";
	cin >> max;

	int *pn = new int[max];

	do
	{
		cout << "Enter a value: ";
		cin >> *pn;
		count++;
	}while (count < max);

	for (int i = 0; i < max; i++)
		sum += *(pn + i);

	cout << "The sum is " << sum << endl;

	return 0;
}
357mag is offline   Reply With Quote