Array homework question.

I have a new homework assignment that has to do with arrays. I am strugling to grasp the concept. I keep reading the chapter over and over but still don't know what to do.
Here is the problem: 1. Write a function
double sum(double a[ ], int n)
that returns the sum a[0]+a[1]+...+a[n-1]. Then write a main program that initializes an
array as follows:
y[0]=1/20 , y[1]=1/21 , y[2]=1/22 ,..., y[n-1]=1/2n-1 .

What should I do?
This is what I have for the first part:
1
2
3
4
5
6
7
void sum (double a[], int n)
{
     
     for (int i = 0; i<n; i++)
     
          
}

Just access element i of the array, and add it to a sum variable.

For the second part, it is basically the same except you are setting the values instead of using them,
How would I do that?

total+= a[i] ???
1
2
3
4
5
6
7
8
9
10
void sum (double a[], int n)
{
     double total;
     
     for (int i = 0; i<n; i++)
     
     total +=a[n];
     
          
}


Like this?
I think this is better. Still not right though.
1
2
3
4
5
6
7
8
9
10
11
void sum (double a[], int n)
{
     double i;
     
     for(i=n-1; i>=0; i--)
{
    sum += a[i];
}
     
          
}
The first one was correct, just make sure to initialize total to 0 and you should be fine.
You'll have to return double as well, and your addition has a little mistake
1
2
3
4
5
6
7
8
9
10
double sum (double a[], int n)
{
     double total=0.0;
     
     for (int i = 0; i<n; i++)
     
     total +=a[i];

     return total;
}
Last edited on
Topic archived. No new replies allowed.