C++ Prefix Average Conversion

I was givin this function to convert to c++ code but i dont understand how to convert the first step a <- new array, i believe i have the rest correct. Any help would be nice

Algorithm prefixAverages1(X, n)

A <- new array of n integers
for i <- 0 to n - 1 do
s <- 0
for j <- 0 to i do
s <- s + X[j]
A[i] <- s / (i + 1)
return A

1
2
3
4
5
6
7
8
9
10
11
12
13
14
double prefixAverages1(int X[], int n)
{
    double A;     
	for(int i = 0; i < n; i++)	
	{
		double s = 0;		
		for(int j = 0; i < n; i++)
		{
			s = s + X[j];		
		A[i] = s / (i + 1); 
		}
	}
	return A; 				
}
You can create a new array with new. You return a pointer to the first time, so the function starts like this:
1
2
3
double* prefixAverages1(int X[], int n)
{
    double *A = new double[n];

Here is the code with this change. Your implementation has some other problems which I've underlined below. I've also changed the indentation to match the actual structure.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
double* prefixAverages1(int X[], int n)
{
    double *A = new double[n];
	for(int i = 0; i < n; i++)	
	{
		double s = 0;		
		for(int j = 0; i < n; i++)
		{
			s = s + X[j];		
			A[i] = s / (i + 1); // not in the right place.
		}
	}
	return A; 				
}

Finally, the algorithm is inefficient. To see why and to see how to fix it, write down 10 random numbers between 1 and 100. Now do the algorithm by hand and write down the answers. You'll quickly see a way to optimize it.
The loop on line 7 does not match your algorithm.
Line 10 should not be in the inner loop.

Why does the algorithm mention array of integers since it stores averages?

Assuming the averages can be double, I do suggest that you use type std::vector<double> for A and naturally as the returntype of the function too.
Ahhh, i see. Thank you, now i understand :)
Topic archived. No new replies allowed.