Max, Min, Avg function for an array in C++ - c++

I am being tasked with writing a function that takes as parameters an array of doubles, the size of the array, and then 3 pass-by-reference parameters called min, max, and avg. My function must: process the array data to find the minimum value (min), maximum value (max), and calculate the average (avg), each of which gets assigned to the corresponding reference parameter so that the calling function will be able to see those values. I am fairly new to coding and am very confused in what my error is the main function included below, any help would be greatly appreciated.
#include <iostream>
using namespace std;
void normalizeMinMaxAvg(double data[], int size,double& min, double&
max, double& avg)
{
max = 0;
min = 0;
//int amount = size;
int count = 0;
int sum = 0;
int i;
avg = 0;
for (i=0; i < size; i++)
{
count++;
sum += i;
if ( i > max)
{
i=max;
}
else if (i < min)
{
i=min;
}
}
avg = sum/count;
}
int main ()
{
double data[]={10.0,0.0,20.0,30.0};
cout << normalizeMinMaxAvg (data, 4, min, max, avg);
return 0;
}

Just provide variables that can be passed to that function, and output these like follows:
int main ()
{
double data[]={10.0,0.0,20.0,30.0};
double min, max, avg;
normalizeMinMaxAvg (data, 4, min, max, avg);
cout << "min = " << min << "\n";
cout << "max = " << max << "\n";
cout << "avg = " << avg << "\n";
return 0;
}
Also inside your function use the data from the array to calculate min and max:
if ( data[i] > max)
{
max = data[i];
}
else if (data[i] < min)
{
min = data[i];
}

Few problems:
deal with the empty data array case first.
set min and max to the first element of the array (not to zero). Think about what if the numbers are all negative. Will max contain the right answer?
You want to find the maximum and minimum elements so you have to use the data contained in data
if ( data[i] > max){
max=data[i];
}
Same goes for the min case.
normalizeMinMaxAvg does not return so you cannot use it in a cout expression. You can print the parameters directly.
Here is a working version of your code.
void normalizeMinMaxAvg(double data[], int size,double& min, double&
max, double& avg)
{
if(size<=0)
return;
min= max = data[0];
int count = 0;
double sum = 0;
int i;
avg = 0;
for (i=1; i < size; i++)
{
count++;
sum += data[i];
if ( data[i] > max)
{
max=data[i];
}
else if (data[i] < min)
{
min=data[i];
}
}
avg = sum/(double)count;
}
int main ()
{
double data[]={10.0,0.0,20.0,30.0};
double min,max,avg;
normalizeMinMaxAvg (data, 4, min, max, avg);
cout<<min<<" "<<max<<" "<<avg<<endl;
return 0;
}

Your problem is that you're not accessing your array's data. Instead you're using your iteration variable i. Basically, on your normalizeMinMaxAvg function, you should do this on your for loop:
for (i=0; i < size; i++){
//count++; - no need for it, you already have size!
sum += data[i];
if ( max > data[i]){
max = data[i];
}
if (min < data[i]){
min = data[i];
}
}
avg = sum/size;
Also you need to declare your variables min, max and avg on your main() function in order to use them when you call your normalizeMinMaxAvg function.

There are a couple of issues with your code. You need to understand how passing arguments by reference works in C++.
void normalizeMinMaxAvg(double data[], int size,double& min, double& max, double& avg)
normalizeMinMaxAvg doesn't return anything - note the void return type - it modifies 3 already existing double variables, so if you are going to call it form main you have to define those variables.
int main()
{
double data[]={10.0,0.0,20.0,30.0};
double min = 0, max = 0, avg = 0; //variables defined and initialized here
//Note the '= 0' on all variables, it's important else they'll have random values
normalizeMinMaxAvg(data, sizeof(data)/sizeof(data[0]), min, max, avg);
//Your function has modified min, max, and avg, so you use them here
std::cout << min << ", " << max << ", " << avg << std::endl;
return 0;
}
Your normalizeMinMaxAvg function also has problems:
void normalizeMinMaxAvg(double data[], int size,double& min, double& max, double& avg)
{
if (size <= 0) //Nothing to do. Might want to add a return error code
return;
//0 is not a sensible value for init, what if all your values are negative?
min = data[0];
max = data[0];
avg = 0;
int sum = 0;
for (i=0; i < size; i++)
{
sum += data[i];
if ( data[i] > max) { //have to access your data by data[i]
max=data[i]; //NOT i=max, you're assigning to max
}
if (data[i] < min) {
min=data[i];
}
}
avg = sum/size;
}

Couple things I noticed:
The values are stored in data[] so you must use data[i] in your loop to check for min, max, and to compute the average.
Also, you want to initialize min to the maximum double value so that it will be replaced by the actual minimum from the data.

You need to be referencing the items in the array. So it should not just simply be i, that is just a number. It should be data[i]. This will refer to the ith element of the array data.

Three things:
You have to define min, max, avg in your main() function before passing them on.
You can't cout << function() if it doesn't return anything.
In normalizeMinMaxAvg for loop, you access i (index) instead of data[i] (the data under index i in array data).

Related

Not sure what to put in my main to get my code to work [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I wrote this code but not sure what to put in my main(), I tried my best to try and figure it out, if someone would please tell me what to do.
Here exactly what I am trying to do:
Program describes what its suppose to do
Prompts the user to enter a number between 1 and 10, and then fills an array with positive floating point number
Outputs the contents of an array of floats, using a function
Use a function to compute the mean, max and min from an array of floats. The values are returned in pass by reference variables
Output the computed value
If at any point the user enters an invalid input, prompt them again
Terminates safely
Here is the code:
//include go here
#include <cstdio>
#include <iostream>
#include <cfloat>
using namespace std;
//Constants go here
const int MAX = 10;
const int MIN = 1
//outputs overview of program to user
void displayOverview();
//prompts user to enter a number between min and max and return it
//validated using a loop
int getIntInRange(int min, int max);
//prompts user to enter a floating point number that is > 0
//validated using a loop
float getPositiveFloat();
//prompts user for size of array (< size)
//fills nums with that many floating point values
int fillArray(float nums[], int size);
//outputs the array
void printArray (float arr[], int Size);
//Computes and returns the mean, maximum, and minimum
void computesValues(float arrr[], int size, float &mean, float &max, float &min);
int main(){
displayOverview();
float myArr[MAX];
int size = fillArray(myArr, MAX);
return 0;
}
//Prompt user to enter a number between Min and max
//If user entered a number within the range, is valid is true
//If user entered a number not within min and max, output sorry not in range
int getIntInRange(int min, int max){
int userInput = -1;
bool isValid = false;
while(!isValid){
printf("Please enter an integer between %d and %d\n", min, max);
scanf("%d", &userInput);
if(min <= userInput && userInput <= max){
isValid = true;
}else{
printf("Sorry, that is not in range\n Please try again\n");
}
}
return userInput;
}
//int numVals
int fillArray(float nums[], int size){
int numVals = getIntInRange(MIN, MAX);
for(int i=0; i< numVals&& i<size ; i++){
nums[i] = getPositiveFloat();
}
return numVals;
}
//Prompt user to enter a positive number
//if User enters a number that is not positive, output "Not a Positive"
float getPositiveFloat(){
float input;
do{
cout << "Please enter a positive number\n";
cin >> input;
if(!(input>0)){
cout << "Not a positive!\n";
}
}while(!(input>0));
return input;
}
//Introduction to the program
void displayOverview(){
cout << "Welcome to my program. You will see how magically I can compute things " <<
"from numbers!!" << endl;
}
//Print an array
void printArray(float arr[], int size){
for (int i = 0; i<size; i++){
cout << arr[i] << " ";
}
}
//Compute Min, max and mean.
void computesValues (float arr[], int size, float &mean, float &max, float &min){
float sum = 0;
for (int i = 0; i<size; i++){
sum = sum + arr[i];
}
mean = sum/size;
max = arr[0];
for (int i = 1; i<size; i++){
if(arr[i] > max)
max = arr[i];
}
min = arr[0];
for (int i = 1; i<size; i++){
if(arr[i] < min)
min = arr[i];
}
printf("mean = %f max = %f min = %f\n", mean, max, min)
}
Main does not call to compute the values from your array.
void computesValues (float arr[], int size, float &mean, float &max, float &min)
Should make the last 3 Float variables local to the function and remove them from the prototype and declaration:
void void computesValues (float &arr[], int size){
float mean{}, max{}, min{};
You can call the printArray function should take const references of min, max, mean, array, and size variables.
void computesValues (float arr[], int size){
float min{}, max{}, mean{};
float sum = 0;
for (int i = 0; i<size; i++){
sum = sum + arr[i];
}
mean = sum/size;
max = arr[0];
for (int i = 1; i<size; i++){
if(arr[i] > max)
max = arr[i];
}
min = arr[0];
for (int i = 1; i<size; i++){
if(arr[i] < min)
min = arr[i];
}
printArray(arr, size, mean, max, min); // call from within your computesValues function
}
//Print an array
void printArray(const float arr[], const int size, const float mean, const float max, const float min){
for (int i = 0; i < size; i++){
cout << arr[i] << " ";
}
printf("mean = %f max = %f min = %f \n", mean, max, min);
}
The original errors with the code above:
printf("mean = %f max = %f min = %f\n", mean, max, min); //<- typo added semi-colon
const int MIN = 1; //<-typo added semi-colon
no declaration of variables min, max, mean in main.
const qualifier should be used for functions that do not modify the values
functions should only do one thing calc / print not both.
Demo

Pointers Relationship with local variable

This is the task that I have performed.
Write a C++ function which accepts an array of integers and the size of the array and finds :
a. Sum of the elements in the array
b. Average of the array elements
c. Minimum and maximum values in the array
In the main program, declare an array of 10 integers using dynamic memory allocation and call
the aforementioned function. Display the output of the function within the main. (Use call by
reference for output values).
//USER DEFINED FUNCTION " func "
void func(int arr[], int size, int *sum, int *avg, int *min, int *max)
{
*sum = 0;
*min = arr[0];
*max = arr[0];
*avg = 0;
//calculations for sum
for (int i = 0; i < size; i++)
{
*sum = *sum + arr[i];
}
//calculations for avg
*avg = *sum / size;
//calculations for minimum
for (int i = 0; i < size; i++)
{
if (*min > arr[i])
*min = arr[i];
}
//calculations for maximum
for (int i = 0; i < size; i++)
{
if (*max < arr[i])
{
*max = arr[i];
}
}
}
void main()
{
int *arr;
int size;
cout << "enter size of array " << endl;
cin >> size;
arr = (int*) calloc(size, sizeof(int));
for (int i = 0; i < size; i++)
{
cout << "enter element : " << endl;
cin >> arr[i];
}
int sum, avg, min, max;
func(arr, size, &sum, &avg, &min, &max);
cout << "sum is : " << sum << "\n avg is : " << avg << endl;
cout << "minimum is : " << min << endl;
cout << "the maximum is : " << max << endl;
getch();
}
Thats my code, its working fine and giving me desired results but is their any alternate for this as well because in the " func " body i am using *min,*max ,*avg because i have passed a value by pointer though i can simply pass value by reference and use " min " instead of " *min " . I want a suggestion on how to pass a value through pointer and yet dont use a dereference operator inside the body of user defined function like here its "func" .
You can use references to achieve what you need.
So your function declaration will change to
func(int arr[], int size, int &sum, int &avg, int &min, int &max)
And inside you can use the variables directly as min, max, avg etc.
In the main you will have to call as
func(arr, size, sum, avg, min, max);
Finally, I will suggest you to create local variables, do all the calculations in them and them finally assign the values to the references passed (This might be a bit optimized in most cases).
To reduce dereference-cluttering, use local variables for the computations and write to the parameters when you're done.
Example:
void sum(const std::vector<int>& numbers, int* result)
{
int total = 0;
for (auto i: numbers)
{
total += i;
}
*result = total;
}
This has a couple of other benefits in addition to readability:
It's faster, because there's no need to constantly read and write through an indirection. (References are just as bad as pointers in this regard.)
It leaves the out parameter unmodified if something throws an exception.

Array element number

I need some help with a simple program. And no - its not my homework (I am learning Cpp for myself and maybe use it in future)
So yeah. I have a program, that reads arrays size 10, and then put numbers in it {2.56, 1.598, 0, 5.15, 0, 3.012, 10, 4.789, 2.569, 0}
The program should ignore the 0, and it does, but the problem is.. I need to get the number of the where the number is placed in array
(Smallest number is 1.598 and its 2 in the array)
Meanwhile I get number 8 on the biggest (should be 5 if zeros would be ignored)
and 1 on the smallest. How can I fix that ?
Heres the void of the biggest number :
void Biggest(float array[], int n, float &max, int &maxNr)
{
max = array[0]
for (int i = 1; i < n; i++){
if (array[i] == 0)
continue;
if (array[i] > max){
max = array[i];
maxNr = i;
}
}
}
Printing void :
void Print(float min, float max, double avg, int maxNr, int minNr)
{
ofstream info;
info.open("result1.txt");
info << "Biggest: " << max << " Number : " << maxNr << endl;
info << "Smallest: " << min << " Number : " << minNr << endl;
info << "Average: " << avg << endl;
info.close();
}
And all main.
int main(){
float array[100];
int n;
float max;
float min;
double avg;
int maxNr, minNr;
Reading(array, n);
Biggest(array, n, max, maxNr);
Smallest(array, n, min, minNr);
Average(array, n, avg);
Printing(min, max, avg, maxNr, minNr);
return 0;
}
First of all, array indexes start at 0, not 1.
If you want to get the position ignoreing zeros, you need to use a separate counter variable from the one used to index the array, so that you don't increment it when you skip over 0.
void Biggest(float array[], int n, float &max, int &maxNr)
{
max = array[0];
int position = 0;
for (int i = 0; i < n; i++){
if (array[i] == 0) {
continue;
}
if (array[i] > max){
max = array[i];
}
position++;
}
maxNr = position;
}
Arrays in most (all that I can think of) programming languages start at index zero. So simply change your for loop condition to be:
for (int i = 0; i < n; i++)
Because you want the loop to start at the first element in the array, i must be initialized to 0. That should fix the problem you are having with the array.

How to call the selection sort function in main

So the question is to Add selection sort function to grade program above. Program should display list of grades in sorted ascending order, we are giving the selection sort function and cant change it, my question is how would I call it from the main function
Here is my code`
#include <iostream>
using namespace std;
double average(double x[], int n);
double maximum(double x[], int n);
double minimum(double x[], int n);
int nAboveAvg(double x[], int n);
void sort(double x[], int npts);
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];
while(grades[i]< 0 || grades[i] > 100)
{
cout<<"Invalid grade- please enter again"<<endl;
cin>>grades[i];
}
}
//call the functions
double avg = average(grades, ngrades);
double max = maximum(grades, ngrades);
double min = minimum(grades, ngrades);
int nAbove = nAboveAvg(grades, ngrades);
//Calling the sort function
sor = sort(grades, ngrades);
//display results
cout << "Average = " << avg << endl;
cout << "# above average = " << nAbove << endl;
cout<<"Max value is = "<<max<<endl;
cout<<"Min value is = "<<min<<endl;
cout<<"Array sorted "<<sor<<endl;
}
void sort(double x[], int npts)
{
double min_value;
int min_index;
double temp;
for(int i= 0; i<npts - 1; i++)
{
for(int j = i + 1; j<npts; j++)
{
if(x[j] < min_value)
{
min_value = x[i];
min_index = j;
}
}
temp = x[min_index];
x[min_index] = x[i];
x[i] = temp;
}
return;
}
`
I think your problem is that you expect the "sort" function to return a value; it does not.
The "sort" function does not return a value, because it was defined with a "void" return value therefore trying to retrieve any data from the variable "sort" will not work (or should not, anyway).
Arrays are passed-in to functions by reference; This means that all of the changes done to the array within the sort function are are still there once the function returns; because of this, you should be outputting the "grades" array, not a non-existent return value.
EDIT: I believe that your problem is at the line:
cout<<"Array sorted "<<sor<<endl;
Trying something like this instead:
for (int i = 0; i < ngrades; ++i)
{
cout << grades[i] << " ";
}
cout << endl;
EDIT 2: Also, change the line:
sor = sort(grades, ngrades);
to just:
sort(grades, ngrades);
EDIT 3: It turns out that there are a few problems with the "sort" function. The first, and worst, problem is that the variable "min_value" is being used without being defined.
Once I changed this, the program would run, but the "sort" function did not work properly.
This brings me to the second problem: The variables "min_value" and "min_index" need to be reset for every iteration of "i".
The final problem is that, within the "j" loop, "min_value" is assigned to "x[i]", whereas it should be assigned to "x[j]":
min_value = x[i];
min_index = j;
should be:
min_value = x[j];
min_index = j;
I fixed the function and tested it to make sure that it works.
Here is the code.
void sort(double x[], int npts)
{
double min_value;
int min_index;
double temp;
for (int i = 0; i < npts - 1; i++)
{
min_value = x[i];
min_index = i;
for (int j = i + 1; j < npts; j++)
{
if (x[j] < min_value)
{
min_value = x[j];
min_index = j;
}
}
temp = x[min_index];
x[min_index] = x[i];
x[i] = temp;
}
return;
}

functions to find average and peak value in c++

my assignment:
program should feature 2 functions, one to calculate the average of the values in the array (returning result as double) and one to find peak value in array (returning result as unsigned value). The array (unsigned ints) and number of values in the array(unsigned int) should be passed through functions as parameters.
Can someone please explain how to fix my code??
#include <iostream>
using namespace std;
#define SIZE 10
double findAverage (unsigned int);
unsigned findPeak (unsigned int);
unsigned numbers [SIZE] = {47, 1, 0, 1324, 99, 1000, 65536, 19, 0, 24000 };
unsigned sum;
unsigned peak;
int main()
{
double average;
for (int i = 0 ; i < SIZE; i++)
{
sum += numbers[i];
}
average = findAverage(numbers[SIZE]);
cout << "The average value is : " << average << endl;
peak = findPeak(numbers[SIZE]);
cout << "The peak value is : " << peak << endl;
}
double findAverage (unsigned sum)
{
double average;
average = sum / SIZE;
return average;
}
unsigned findPeak (unsigned int *)
{
for (int i = 0 ; i < SIZE; i++)
{
if (numbers[i] > peak)
{
peak = numbers[i];
}
}
return peak;
}
From the assignment description:
The array (unsigned ints) and number of values in the array(unsigned
int) should be passed through functions as parameters.
And where are there the two parameters in the functions?
double findAverage (unsigned int);
unsigned findPeak (unsigned int);
The functions can be defined the following way
double findAverage( const unsigned int a[], unsigned int n )
{
double sum = 0.0;
for ( unsigned int i = 0; i < n; i++ ) sum += a[i];
return n == 0 ? sum : sum / n;
}
unsigned int findPeak( const unsigned int a[], unsigned int n )
{
unsigned int max = 0;
for ( unsigned int i = 1; i < n; i++ )
{
if ( a[max] < a[i] ) max = i;
}
return max;
}
I defined function findPeak such a way that it retursn the index of the maximum element. You may rewrite it that it would return the maximum element itself.
Take into account that these tasks can be done with using standard algorithms std::accumulate and std::max_element declared respectively in headers <numeric> and
<algorithm>.
Also there is no any need to define your varaibles in the global namepsace. They could be defined like local variables of main.
You're passing numbers[SIZE] to findAverage instead of sum.
The parameter's name is missing in findPeak's definition.
Also, numbers[SIZE] is not in the array, numbers[SIZE-1] is the last element of the array, because indexing starts at 0.
It's also not a good idea to specify the size of the array and add the elements by hand (in {}). You can easily make a mistake.
Also, you should put all the code in the functions. So in main, you just call them. Don't use global variables either, they aren't necessary here at all and can cause all sorts of problems in bigger projects. So don't get used to bad habits.
Just put your variables in main and pass them to the functions as parameters.
(You're actually doing this, but currently it's unnecessary because for example sum is global.)
Your functions should be independent and reusable:
They should not rely on SIZE
They should not directly use the array: the array with the size should be parameters. Pass as const (no need to modify the array).
Below an example:
double findAverage (const unsigned myArray[], int arraySize)
{
unsigned sum = 0;
double average = 0.0;
for (int i = 0 ; i < arraySize; i++)
{
sum += myArray[i];
}
if (arraySize) average = sum / arraySize;
return average;
}
unsigned findPeak (const unsigned myArray[], int arraySize)
{
unsigned peak = 0;
for (int i = 0 ; i < arraySize; i++)
{
if (myArray[i] > peak)
{
peak = numbers[i];
}
}
return peak;
}
The call:
average = findAverage(numbers, SIZE);
peak = findPeak(numbers,SIZE);
Here a running version:
#include <iostream>
using namespace std;
double findAverage (unsigned int *, unsigned int);
unsigned int findPeak (unsigned int *, unsigned int);
int main()
{
const int size = 10;
unsigned int numbers [] = {47, 1, 0, 1324, 99, 1000, 65536, 19, 0, 24000 };
double average = findAverage(numbers, size);
cout << "The average value is : " << average << endl;
unsigned int peak = findPeak(numbers, size);
cout << "The peak value is : " << peak << endl;
}
double findAverage (unsigned int *numbers, unsigned int size)
{
unsigned int sum = 0;
for (int i = 0 ; i < size; i++)
{
sum += numbers[i];
}
double average = (double)sum / size;
return average;
}
unsigned int findPeak (unsigned int *numbers, unsigned int size)
{
unsigned int peak = 0;
for (int i = 0 ; i < size; i++)
{
if (numbers[i] > peak)
{
peak = numbers[i];
}
}
return peak;
}
Remarks:
You should avoid global variables.
I think the sum calculation makes more sense in findAverage(). Then it has to get passed the array.
The declaration of findPeak missed a *, it did not match the definition.
To pass an array, you must not provide any [...]. Just pass the pointer to the first element by writing the array name.
average = sum / SIZE; firstly evaluates sum / SIZE by doing an integer division, so the result is truncated. You have to cast one of the operands to force a double division.