John
John

Reputation: 11

How to do simple average calculation using a function & calling it?

I need to learn how to use the function for the calculation and then a simple call in main. When I tried it didn't work. I have no idea what to do. It works but when I take out the code from main it gets funky. this is simple simple scenario and code for that.

Write a function that takes an array of ints, and the size of the array - another int. It also returns a double. Call this one 'average.' Return a double that is the average of the values in the array. Demonstrate that it works by finding the average of an array with these values {78, 90, 56, 99, 88, 68, 92}

    #include <stdio.h>
    #include <stdlib.h>

// Outside of main, a function will be declared that takes an array of ints.
double Function(int Array[7])
{
// int Array[7] = {78, 90, 56, 99, 88, 68, 92};
    int sum = 0;
    int i;
    double average;

        // This for loop allows us to use all 7 elements in the array.
    for(i=0; i<7; i++)
    {
            // This takes all the array's elements and sums them up.
    sum += Array[i];
    }
            // This prints the sum
    printf("Sum = %d\n", sum);

        // The double average is found by taking the sum found and dividing it by 7.
    average = sum/7;
        // This prints the average in a double.
    printf("The resulting average is %lf \n", average);
    return average;

    }  // Ends Function

// There will also be the size of the array(which is another int)
// The function will return a double called average. It is the average of the values in the array.

    int main()
    {



//int i;  // Allows us to use the for loop and print each element in the corresponding array.
    // int array numbers are declared and initialized.
    int Array[7] = {78, 90, 56, 99, 88, 68, 92};
    int sum = 0;
    int i;
    double average;

    // This for loop allows us to use all 7 elements in the array.
    for(i=0; i<7; i++)
        {
        // This takes all the array's elements and sums them up.
        sum += Array[i];
        }
        // This prints the sum
        printf("Sum = %d\n", sum);

    // The double average is found by taking the sum found and dividing it by 7.
    average = sum/7;
    // This prints the average in a double.
    printf("The resulting average is %lf \n", average);

    Function(Array);



system("pause");
return 0;
}

Can any one give me a tips!

Upvotes: 0

Views: 13737

Answers (3)

user3629249
user3629249

Reputation: 16540

the posted code contains several misconceptions

  1. no need to '#include' header files those contents are not needed.
  2. only write code that is part of the solving of the problem. Other code that is added for 'debug' purposes should be eliminated from the final executable. Usually be surrounding the debug code with: #ifndef NDEBUG .... #endif Suggest learning how to work with NDEBUG
  3. The problem only needs to solved once, not both in 'main()' and in 'Function()' BTW: function is a terrible function name suggest: calculateAverage(). Function names should indicate what they will perform, usually by starting the function with some active verb, like calculate
  4. for ease of readability and understanding, consistently indent the code. Indent after every opening brace '{'. unindent before every closing brace '}'. Suggest each indent level be 4 spaces as that is wide enough to be visible even with variable width fonts. Remember, the compiler (in general) doesn't care about the 'style' of the code formatting. However, any human cares a lot, because the human wants to be able to read the code.
  5. it is (almost always) a bad idea to hard code any values other than 0 and 1. Instead give them meaningful names via a enum statement or #define statements, then use those meaningful names throughout the code.
  6. Please pay attention to these 3 details in the code:

    • how the size of the array is calculated
    • how the parameters are passed to the 'Function()'
    • how the average is calculated.

Note: when all the variables in a divide operation are integers, then a integer divide is performed. This can produce some surprising results. For instance, 5/3 results in 1, not 1.66. by wanting to keep the fraction, cast one of the elements (not the whole expression) to double or float

and now the code

#include <stdio.h> // printf()
//#include <stdlib.h>

double Function(int *pArray, int numElements );

int main( void )
{
    // int array numbers are declared and initialized.
    // note: usually best to let the compiler calculate array size
    //       rather than hardcoding the size
    int Array[] = {78, 90, 56, 99, 88, 68, 92};

    // number of elements in array
    int sizeofArray = sizeof(Array)/sizeof(int);

    // call Function to calculate and return as double,
    // the average of the array elements
    double average = Function( Array, sizeofArray );

    // This prints the average as a 'double'.
    printf("The resulting average is %lf \n", average);

    //system("pause"); // not portable, suggest:
    int ch;
    while( (ch = getchar()) != EOF && '\n' != ch );
    getchar();

    //return 0;   // <-- in modern C, if main to return 0 then this line not needed
} // end function: main


double Function(int *pArray, int numInts )
{
    int sum = 0;

    double average;

    for(int i=0; i<numInts; i++)
    {
        sum += pArray[i];
    }

    // cast one of the values as a double so an integer divide is NOT performed
    average = (double)sum / numInts;

    return average;
}  // end function: Function

Upvotes: 0

JgWangdu
JgWangdu

Reputation: 317

In C Program execution always starts from main. So the stack will be like

main()-->Function()

You are almost right just you called the function which returns the average so to keep that average or to accept that average in main you need variable so just remove all the code shown below

for(i=0; i<7; i++)
    {
    // This takes all the array's elements and sums them up.
    sum += Array[i];
    }
    // This prints the sum
    printf("Sum = %d\n", sum);

// The double average is found by taking the sum found and dividing it by 7.
average = sum/7;
// This prints the average in a double.
printf("The resulting average is %lf \n", average);

Now take the results returned by the Function() in average variable shown below.

average=Function(Array);

Now print that value if you want to print or use in main if you need.

Upvotes: 0

SHG
SHG

Reputation: 2616

If you want to follow the instruction you were given, your function declaration should be

double average(int *array, int array_size)

Also, your solution should be general, not only for array with length of 7.

In general in C language - when you want to pass an array which its length is unknown, you pass the address of the array (here *array) and its size (here array_size). Then your function will iterate over the array from the given address, with jumps of the type (here jumps of sizeof(int) because it's an array of ints).

Upvotes: 1

Related Questions