Calculate average from an array - c++

I tried to calculate average and when I enter 1 2 3 0 , the average is 2.00 but when I enter 10 20 90 100 0,the average is 227871776.00. I am not able to identify what is going wrong here. I feel like my sum and count is not working properly but I can't figure out why.
double calculateAverage(int numbers[], int count )
{
int sum = 0;
double average;
while (count < arraysize && numbers[count] != 0)
{
count ++;
}
for (int i= 0 ; i < count; i++)
{
sum += numbers[i];
}
average = static_cast<double>(sum) /count;
return average;
}

Why bother even making your own count loop, when you have std:accumulate.
#include <numeric>
#include <iostream>
double calculateAverage(int numbers[], size_t count)
{
int sum = std::accumulate(numbers, numbers + count, 0);
return sum / count;
}
int main()
{
//int numbers[] = {1, 2, 3, 4, 5};
int numbers[] = {10, 20, 90, 100};
std::cout << "average is " <<
calculateAverage(numbers, sizeof(numbers) / sizeof(int)) << '\n';
}
Your code was quite confused. Why pass a count if you're going to count the array anyway? Also 0 is a valid value in the array and so it makes a flawed sentinel value.

#include<iostream>
using namespace std;
double calculateAverage(int numbers[], int count )
{
int sum = 0; //sum is used to add all the values in the array
double average;
for (int i= 0 ; i < count; i++)
sum += numbers[i];
average = static_cast<double>(sum) /count;
return average;
}
int main()
{
int lim; //size of the array
cout<<"Enter the number of elements in array\n";
cin>>lim;
cout<<"Enter the values \n";
int num[lim]; //the array is initialized to desired size
for(int i=0;i<lim;i++)
cin>>num[i]; //the values are taken from user
cout<<"\nAverage = "<<calculateAverage(num,lim)<<"\n"; //the array and the size of array is passed to calculate average function or you can even calculate size of array using (sizeof(array)/sizeof(array[firstelement])
return 0;
}

Recreate the code overall
It is hard to understand (your code).
Mine:
double calculateAverage(double numbers[], double count )
{
double sum = 0;
double average=0;
for(int counter=0;counter<count;counter++)
{
sum+=numbers[counter];
}
cout<<sum<<"\n";
average=sum/count;
return average;
}
Explaination:
First the function will take an array of double
and count is how many is there in the array (I tried to stick into your code)
The for loop runs based on the count variable.
the sum adds the value of the element in the array numbers.
Divide to get the average.

numbers[count] != 0 could produce errors when you have 0 appear earlier in the array. Also, where do you initialize arraysize? It could be null somehow or a very weird number. I recommend calling the numbers length instead. But there's no reason to use the while loop bc you have an array size already known

Related

check if the array can be split to subarrays which are equal in sum

my problem i face is i cant run my code when i use cin>>arr
can i make it work with this code
#include <bits/stdc++.h>
using namespace std;
int checkEqualSumUtil(int arr[1000], int N,
int sm1, int sm2,
int sm3, int j)
{
if (j == N)
{
if (sm1 == sm2 && sm2 == sm3)
return 1;
else
return 0;
}
else
{
int l = checkEqualSumUtil(arr, N,
sm1 + arr[j],
sm2, sm3, j + 1);
int m = checkEqualSumUtil(arr, N, sm1,
sm2 + arr[j],
sm3, j + 1);
int r = checkEqualSumUtil(arr, N, sm1, sm2,
sm3 + arr[j], j + 1);
return max(max(l, m), r);
}
}
void checkEqualSum(int arr[], int N)
{
int sum1, sum2, sum3;
sum1 = sum2 = sum3 = 0;
if (checkEqualSumUtil(arr, N, sum1,
sum2, sum3, 0)== 1)
{
cout << "YES";
}
else
{
cout << "NO";
}
}
int main()
{
int n;
cin>>n;
int arr[n/2];
for(int i=0;i<n;i++){
cin>>arr[i];
int N = sizeof(arr) / sizeof(arr[0]);
checkEqualSum(arr, N);
return 0;
}}
my code
i have edited my code the input is typed correctly
but it always outputs no
i dont know why any ideas??
also thank you for helping me all
i tried the input
3
1 1 1
it should print yes
put the output is no?
Let's analyze your code in main:
int main()
{
int arr[1000],n;
You have allocated an array, arr, that has a capacity of 1000 integers.
The array is not initialized.
An alternative declaration:
const unsigned int N = 1000;
int array[N];
The statement below reads the quantity of numbers to read into the array.
cin>>n;
If the User or Operator enters a value larger than 1000, you will have undefined behavior. Quantities less than 1000 are a waste of space. Use std::vector<int> to contain elements when the capacity is not known during runtime.
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
Here you are calculating the capacity of the array. The capacity was already declared as 1000. See my suggestion about using N as the capacity.
int N = sizeof(arr) / sizeof(arr[0]);
The above line is not necessary. Another option is to use a macro:
#define MAXIMUM_NUMBERS (1000)
The present form of the statement below, tells the function to use 1000 values, regardless of the quantity of numbers entered by the User.
checkEqualSum(arr, N);
For example, if I enter 5 numbers, the function call will translate to:
checkEqualSum(arr, 1000);
This because you initialized N to the capacity of the array.
Maybe you want to pass the quantity of numbers read into the array:
checkEqualSum(arr, n);
This is why variable names should differ in more than case.
This code is fine, telling the Operating System that your code run with no errors.
return 0;
}

How many numbers higher than average [C++]

I filled an array with 30 random numbers and calculated average. I want to display how many numbers are higher than the average. I tried making a function "aboveAverage" and check if the numbers are higher than the average and than just increase the count "num_over_average++". The problem is I don't know how to pass a value "avg" from function to another function.
#include <iostream>
#include <ctime>
using namespace std;
const int n = 30;
void fillArray(int age[], int n) {
srand(time(NULL));
for (int index = 0; index < n; index++) {
age[index] = (rand() % 81) + 8;
}
}
void printArray(int age[], int n) {
for (int index = 0; index < n; index++) {
cout << age[index] << endl;
}
}
double printAverage(int age[], int n) {
double sum;
double avg = 0.0;
for (int i = 0; i < n; i++) {
sum = sum + age[i];
}
avg = ((double) sum) / n;
cout << avg << endl;
return avg;
}
void aboveAverage(int age[], int n) {
double avg;
int num_over_average = 0;
for(int i = 0; i < n; i++){
if(age[i] > avg) {
num_over_average++;
}
}
cout<<num_over_average;
}
int main(int argc, char *argv[]) {
int age[n];
fillArray(age, n);
cout << "array: " << endl;
printArray(age, n);
cout << endl;
aboveAverage(age, n);
//example: Days above average: 16
}
This should be a comment, but I don't have enough reps :(
Change aboveAverage to void aboveAverage(int age[], int n, double avg)
Return avg from printAverage function
Change the last part of your main code to
double avg;
avg = printAverage(age, n);
aboveAverage(age, n, avg);
Hope this helps!
You have two solutions using your code:
Either you call printAverage() to initialise avg in aboveAverage() :
void aboveAverage(int age[], int n) {
double avg = printAverage();
...
}
Or you pass the average at parameter of aboveAverage() after having computed it with printAverage() :
void aboveAverage(int age[], int n, double avg) {
...
}
If you use the standard library you can do that with two lines of code:
double average = std::accumulate(std::begin(age), std::end(age), 0.0) / std::size(age);
int above_average = std::count_if(std::begin(age), std::end(age),
[average](double value) { return average < value; });
Okay, you might count that as three lines.
One major advantage of this approach over the code in the question is that you can change the container type to, say, vector<double> without having to change any of this code.
Well is pretty simple but dependent on your situation, I'll elaborate.
I'm the case when it's part of a bigger function (do-somthing())
You could calculate the average value like so and pass it to your "aboveAverage" function and print it:
double n_average = printAverage(nArr_ages, n_agesArraySize);
aboveAverage(nArr_ages, n_agesArraySize, n_averag);
Myself would probably rewrite the printAverage function as two functions, one that returns the average value based on the array and another that prints it not both at once because it violates the SOLID principals of a single responsibility and that a function name should reflect exactly what it does, in this case maybe calculateAverage or getAverageAge or any other appropriate name will do (try and name your functions like the english language so your code will be read like a song.
For example:
const size_t n = 30;
double calculateAverage(int nArr_ages[], int n_agesArraySize) {
double sum = 0.0;
double avg = 0.0;
for (int indexInArray = 0; indexInArray < n_agesArraySize; indexInArray++) {
sum = sum + age[indexInArray];
}
average = ((double) sum) / n_agesArraySize;
return average;
}
int aboveAverageCells(int ages[], int n_agesArraySize ) {
double average = calculateAverage(ages, n);
int num_over_average = 0;
for(int indexInArray = 0; indexInArray < n_agesArraySize; indexInArray++) {
if(ages[indexInArray] > avg) {
num_over_average++;
}
}
return num_over_average;
}
Now just call them in order, save the returned values to local variables in the main function and print using cout also locally in main.
As a side note next time maybe choose different names for the const and the local functions variable for the array size.

Functions and arrays

The question is
Design the grade processing program to use functions and an array. Let user enter number of grades (set the maximum to 50). Store grades in an array. Create a separate function for each calculation (total of 3 functions): 1) average grade, 2) maximum grade, 3) number of grades above the average. Display all results.
I think I got the main part, but I'm having trouble with how to write the functions, the functions are outputting one for some reason, and I'm having trouble writing the max function or how to start it.
#include <iostream>
using namespace std;
double average(double x[], int n);
double maximum(double x[], int n);
int nAboveAvg(double x[], int n);
int main()
{
double grades[50];
int ngrades;
cout<<"How many grades? (max = 50)";
cin>>ngrades;
//create for loop to get grades from user
for(int i = 0; i<ngrades; i++)
{
cout<<"Enter grade ";
cin>> grades[i];
}
//call the functions
double avg = average(grades, ngrades);
double max = maximum(grades, ngrades);
int nAbove = nAboveAvg(grades, ngrades);
//display results
cout<<"Average = "<<avg<<endl;
cout<<"# above average = "<<nAbove<<endl;
}
double average(double x[], int npts) //define the functon to recieve the array
{
double sum = 0;
for(int k = 0; k<npts; k++)
{
sum = sum +x[k];
}
return sum / npts;
}
double maximum(double x[], int npts)
{
double max = 0;
for(int i = 0; i<npts; i++)
{
if(max == npts)
{
return max;
}
if(max < npts)
{
return npts;
}
}
}
int nAboveAvg(double x[], int npts)
{
int nAboveAvg = 0;
for(int i = 0; i<npts;i++)
{
if(x[i] > npts)
{
nAboveAvg++;
}
}
return nAboveAvg;
}
Incorrect Printing
//call the functions
double avg = average(grades, ngrades);
double max = maximum(grades, ngrades);
int nAbove = nAboveAvg(grades, ngrades);
Notice that you define variables named avg and nAbove.
//display results
cout<<"Average = "<<average<<endl;
cout<<"# above average = "<<nAboveAvg<<endl;
But then you use average and nAboveAvg (the functions) when you attempt to print the results.
The correct version here would be:
cout << "Average = " << avg << endl;
cout << "# above average = " << nAbove << endl;
Compiler Warnings
When I try to compile this, the compiler emits a number of warnings. e.g.
main.cpp: In function 'int main()':
main.cpp:29:24: warning: the address of 'double average(double*, int)' will always evaluate as 'true' [-Waddress]
cout<<"Average = "<<average<<endl;
or
main.cpp:24:11: warning: unused variable 'avg' [-Wunused-variable]
double avg = average(grades, ngrades);
It is a good idea not to ignore those warnings.
Count Above Average
if(x[i] > npts)
{
nAboveAvg++;
}
You compare the value at position i with number of input values.
However, you should be comparing value at position i with the average of all the values. Hence
int nAboveAvg(double x[], int npts)
{
int count = 0;
double avg = average(x, npts);
for (int i(0); i < npts; ++i) {
if (x[i] > avg) {
++count;
}
}
return count;
}
Refactoring
You may now notice that in our program we end up calculating the average value twice. We can fix this by making our function more general -- instead of counting number of values above average, let's count the number of values above arbitrary target passed as a parameter.
int count_above(double x[], int npts, double target)
{
int count = 0;
for (int i(0); i < npts; ++i) {
if (x[i] > target) {
++count;
}
}
return count;
}
Now we can write
//call the functions
double avg = average(grades, ngrades);
double max = maximum(grades, ngrades);
int nAbove = count_above(grades, ngrades, avg);
Maximum Value
Let's think about the algorithm, and start from simplest case -- only one value in the array. In this scenario the first value is also the maximum.
double max = x[0];
Knowing that, let's consider how to find the maximum when there are 2 values in the input array. We already know the maximum of all the values before the second value. Therefore
if (x[1] > max) {
max = x[1];
}
Next step, input array with 3 values. Again, we already know the maximum of all the values before the third value. Therefore
if (x[2] > max) {
max = x[2];
}
We can see a pattern repeating here, which we can wrap in a loop.
double maximum(double x[], int npts)
{
if (npts <= 0) {
exit(-1); // Error...
}
double max = x[0];
for (int i(1); i < npts; ++i) {
if (x[i] > max) {
max = x[i];
}
}
return max;
}
Validating Input
You don't have any validation of the input passed to your functions, yet there are some obvious cases that need to be accounted for.
In all of your functions, what should happen when the npts is negative?
What's the average value of a 0 elements?
What's the maximum value of 0 elements?
A very simple way to handle those cases would be to return some special value as a result. You then have to check the results for this value every time you call the function. In many cases it may be hard to select an appropriate value for this.
Another possibility that would be accepted at a beginner level, would be simply printing some error message to console, and exiting the program. For example
if (npts <= 0) {
cerr << "Too few values in input array." << endl;
exit(-1); // Error...
}
The proper C++ approach would be to throw an exception, for example std::invalid_argument. For example
#include <stdexcept>
// ....
if (npts <= 0) {
throw std::invalid_argument("Too few values in input array.);
}
The "average" function looks good. In the last 2 lines in main, I think you want to output avg instead of average (because average is the name of the function, not the name of the variable that holds the computed value). Similarly, output nAbove instead of nAboveAvg.
The maximum function looks like an empty implementation. I don't think that will compile because it needs to (at least) return a double value.
In the nAboveAvg function, "x[i] > npts" seems like the wrong test. I think you want to compare x[i] to avg (you will want to pass avg into this function as an argument.

Using a function to find the average of an array C++

the purpose of this task is to find the average of an array but not within the main, I have to call a function to do the sum and show the average.
I though my code was sound but it just returns " the average is 011014F1"
I have tried a few different ways of doing the function but I've gone wrong somewhere, maybe everywhere!
Just a heads up, im just starting out with programing.
Heres my code:
#include <iostream>
#include <vector>
using namespace std;
void printArray(int theArray[], int sizeOfarray);
float average(float numbers[], float size, float arrayAverage);
int main()
{
int array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
printArray(array, 10);
cout << "The average is: " << average << endl;
return 0;
}
void printArray(int theArray[], int sizeOfarray)
{
for (int x = 0; x < sizeOfarray; x++)
{
cout << theArray[x] << endl;
}
}
float average(float numbers[], float size, float arrayAverage)
{
double sum = 0.0;
for (int x = 0; x < size; x++)
{
sum += numbers[x];
arrayAverage = sum / size;
}
return (arrayAverage);
}
I had the float average function initially set as a float with int for 'numbers', 'size' and 'arrayAverage' but thought i would change them all to float so they dont clash. like converting an int to a float etc..
As i said im new to this so my logic is not really there but i think im n the right tracks.
Any idea why its returning 011014F1 and numbers like that instead of just the average of 1-10?
Any tips much appreciated!
average is a function, which you need to call, and print what it returns. What you are printing now is the address of that function.
There are a number of problems here. First:
cout << "The average is: " << average << endl;
This is simply printing out the address of the average function, not calling it. What you wanted to do was:
cout << "The average is: " << average(array, 10, 0) << endl;
Second, your method signature has all kinds of type missmatches. The expected array value type is float, yet you're passing it an array of int. This won't work, as the compiler will not allow the implicit conversion from int[] to float[]. Your size argument should be an int in the method signature as well, not float, since array sizes are always integers.
Third, the arrayAverage parameter seems to have no purpose except to possibly throw off your math. You use it as a running accumulator, which is fine, but there's no reason to pass it to the function, it could just be a local value. So, your method signature should look like this:
float average(float numbers[], int size);
Finally, your math for calulating the average of an array is wrong. You do:
for (int x = 0; x < size; x++)
{
sum += numbers[x];
arrayAverage = sum / size;
}
Particularly, the arrayAverage = sum / size is wrong. Or rather, is only right during the final loop iteration. Meaning this is just wasted math. It should be:
float average(float numbers[], int size) {
double sum = 0;
for (int x = 0; x < size; x++)
{
sum += numbers[x];
}
return sum /(double)size;
}
You are not passing any thing to your function average, float average(float numbers[], float size, float arrayAverage)You should pass your array as first parameter and the size of the array in the second, the third one you dont need it , I recommand you to delete itYour function will be :
float average(float numbers[], float size)
{
float average;
double sum = 0.0;
for (int x = 0; x < size; x++)
{
sum += numbers[x];
arrayAverage = sum / size;
}
return (average);
}
and in your main you do a float averageResult = average(array, size);
qDebug()《 averageResult;
#include <iostream>
#include <vector>
using namespace std;
void printArray(int theArray[], int sizeOfarray);
int main()
{
int array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
printArray(array, 10);
return 0;
}
void printArray(int theArray[], int sizeOfarray)
{
for (int x = 0; x < len(theArray); x++)
{
average = average + theArray[x]
}
average = average/(len(theArray));
cout << average;
}

Pass an array through a function

I'm trying to pass a simple array through a function to compute the mean.
int main()
{
int n = 0; // the number of grades in the array
double *a; // the array of grades
cout << "Enter number of scores: ";
cin >> n;
a = new double[n]; // the array of grades set
// to the size of the user input
cout << "Enter scores separated by blanks: ";
for(int i=0; i<n; i++)
{
cin >> a[i];
}
computeMean(a, n);
}
double computeMean (double values[ ], int n)
{
double sum;
double mean = 0;
mean += (*values/n);
return mean;
}
Right now the code is only taking the mean of the last number that was inputted.
There's no loop in your function. It should be something like:
double sum = 0;
for (int i = 0; i != n; ++i)
sum += values[i];
return sum / n;
I'm surprised your current version only takes the last number, it should only take the first number, since *values is the same as values[0].
A better solution uses idiomatic C++:
return std::accumulate(values, values + n, 0.0) / n;
std::accumulate should do the trick.
#include <numeric>
double computeMean (double values[ ], int n) {
return std::accumulate( values, values + n, 0. ) / n;
}
Is this a homework question?
You nead to step through all of the values in your array. You're currently outputting the first number in the array divided by the number of items.