if you could help me with this function!!

Hey, pretty new here, would post more but don't have a huge amount to offer at the moment but I'm cracking the books so I can be a bigger part of the coding community.

So i'm learning arrays and how to pass arrays through functions, cool stuff. But I have a program that takes 10 integers and adds them, fairly simple. I figured out a way to average it and cout the average directly in the sumArray function, but what I would like is to make a specific function that finds the mean.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;

int sumArray (int values[], int breadth)
{
    int sum = 0;
// this array stops when i == size. Why? The last element is size - 1
    for ( int i = 0; i < breadth; i++ )
{
    sum += values[ i ];
}
    return sum;
}
int main ()
{
int values[ 10 ];
for ( int i = 0; i < 10; i++ )
{
cout << "Enter value " << i << ": ";
cin >> values[ i ];
}
cout << sumArray( values, 10 ) << endl;
}


if there was a way to pass the result of sumArray (values, 10) into a function and divide it by the size (10)? or something idk, if you could explain the reasoning behind your answer that would be awesome!

Thank you
You could have an averageArray function(arrayName, arraySize) that first calls the sumArray function to add up all the array values, then the average function could divide the result it receives from the sum function by the size of the array. Just keeping in mind that if all the numbers are integers, the result would be integer division. You could cast numbers to float or double to avoid integer division.

1
2
// this array stops when i == size. Why? The last element is size - 1
    for ( int i = 0; i < breadth; i++ )


If breadth is 10, the for loop will work for all elements 0 through 9. i then increments one more time to 10 - at which point it will no longer be less than breadth (10) and the loop will be exited.
Last edited on
Topic archived. No new replies allowed.