Link to home
Start Free TrialLog in
Avatar of amlegacy
amlegacy

asked on

Calculating class grade average using arrays

HI,

I'm trying to create an array to calculate the class grade average. I only want to return the answer for grades[4]. I haven't been shown how to pass one element.

#include <iostream>

void my_average (double score [], int elements);

int main (void)

{

      double ans [5] = {0};
      my_average (ans, 5);


      return 0;
}

void my_average (double score [], int elements)

{

      double  grades [5];

      grades[0] = 88;
      grades[1] = 65;
      grades[2] = 99;
      grades[3] = 110;
      grades[4] = ((grades[0] + grades[1] + grades[2] + grades[3])/400); //calculates the average
}
Avatar of Infinity08
Infinity08
Flag of Belgium image

You're creating a new array inside the my_average function. You shouldn't - you can just re-use the one passed as a parameter :

void my_average (double score [], int elements)

{
      score[0] = 88;
      score[1] = 65;
      score[2] = 99;
      score[3] = 110;
      score[4] = ((grades[0] + grades[1] + grades[2] + grades[3])/400); //calculates the average
}
Of course I meant this :

void my_average (double score [], int elements)

{
      score[0] = 88;
      score[1] = 65;
      score[2] = 99;
      score[3] = 110;
      score[4] = ((score[0] + score[1] + score[2] + score[3])/400); //calculates the average
}
ASKER CERTIFIED SOLUTION
Avatar of Infinity08
Infinity08
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Take a look at this tutorial on functions :

        http://www.cplusplus.com/doc/tutorial/functions.html

(ignore the C++ specific stuff - just focus on the function call mechanics)

Feel free to ask for clarification if anything I said isn't clear.
Avatar of amlegacy
amlegacy

ASKER

Ok. Thank you. I didn't know you can do that. If I just wanted to pass the 5th element of the array and not all of the arrays. How would I do that?
Ok. I'll look into to your suggestions.
The fifth element is just a double, so you can pass just a double, like this :

        void fun(double value) {                               /* <--- the function */
            /* do something with value */
        }

and call it like this :

        double array[10];
        /* fill the array */
        fun(array[5]);                /* we pass the element at index 5 in the array to the function */

But that's not what you want to do with your average function.
Give it a try with all the suggestions I made, and post your new code here. I'll be happy to review it, and help you further if needed.