functions to find average and peak value in c++ - 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.

Related

C++ array assistance

I am getting an error in the word sum where it says average = sum / ARRAY_SIZE;. It is saying that the sum is undeclared. Even though I use sum previously in the getSum function, I only get the error here. I tried declaring it as a variable at the top but I am still getting that error. I do not know how else to declare it in a way that would stop this error.
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
// Function prototypes
int getHighest(int numbers[],int ARRAY_SIZE);
int getLowest(int numbers[],int ARRAY_SIZE);
int getSum(int numbers[],int ARRAY_SIZE);
int getAverage(int numbers[],int ARRAY_SIZE);
int main () {
// Variables
const int ARRAY_SIZE = 12; // Array size
int numbers [ARRAY_SIZE]; // Array with 12 integers
int count = 0; // loop counter variable
string filename;
// Open file
cout << "Enter input filename:";
cin >> filename;
ifstream inputFile(filename); // input file stream object
// Read numbers from file into array
while(count <ARRAY_SIZE && inputFile >> numbers[count])
count ++;
// Print results
cout<<ARRAY_SIZE<<" numbers read from input file."<<endl;
cout<<"The highest value is: "<<getHighest(numbers,ARRAY_SIZE)<<endl;
cout<<"The lowest value is: "<<getLowest(numbers,ARRAY_SIZE)<<endl;
cout<<"The sum of the numbers is: "<<getSum(numbers,ARRAY_SIZE)<<endl;
cout<<"The average of the numbers is: "<<getAverage(numbers,ARRAY_SIZE)<<endl;
}
int getHighest( const int numbers[], int ARRAY_SIZE)
{
int highest;
highest = numbers[0];
for(int count = 1 ; count < ARRAY_SIZE; count++)
{
if (numbers[count] > highest)
highest = numbers[count];
}
return highest;
}
int getLowest(const int numbers[], int ARRAY_SIZE)
{
int lowest;
lowest = numbers[0];
for (int count = 1; count < ARRAY_SIZE; count++)
{
if (numbers[count] < lowest)
lowest = numbers[count];
}
return lowest;
}
int getSum(const int numbers[], int ARRAY_SIZE)
{
int sum = 0;
for(int count = 0; count < ARRAY_SIZE; count++)
sum+= numbers[count];
return sum;
}
int getAverage(const int numbers[], int ARRAY_SIZE)
{
int average = 0;
for (int count = 0; count < ARRAY_SIZE; count++)
average = sum / ARRAY_SIZE;
return average;
}
It is saying that the sum is undeclared. Even though I use sum previously in the getSum function, I only get the error here.
sum is only a local variable in getSum so it cannot be accessed from getAverage, and in fact that variable does not exist anymore when you leave getSum
Note also the for in getAverage is useless because you do all the time average = sum / ARRAY_SIZE; whose value is always the same, so you want :
int getAverage(const int numbers[], int ARRAY_SIZE)
{
return getSum(numbers, ARRAY_SIZE) / ARRAY_SIZE;
}
Note your declarations and definitions do not correspond because in your definitions the array is const but not in your declarations. Put the array also const in the declarations :
int getHighest(const int numbers[],int ARRAY_SIZE);
int getLowest(const int numbers[],int ARRAYSIZE);
int getSum(const int numbers[],int SIZE);
int getAverage(const int numbers[],int SIZE);
may be also rename ARRAY_SIZE to size to not confuse with the global variable of the same name (even they receive its value), and SIZE to size because uppercase are generally not used to name a local variable/parameter.
Out of that, you are in C++, are you sure you want to use (C) arrays rather than for instance std::vector allowing to not give the size in argument to each functions and also to have iterators and predefined operations etc ?

Max, Min, Avg function for an array in 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).

C++ Program To Find Smallest and Largest Number In Array

Beginner in C++ here and learning arrays. The program below is supposed to return the smallest and largest number in an array using two separate functions. One for the largest and one for the smallest number. However, it is returning 0 all the time for function lastLowestIndex and I am unsure what I may be doing wrong.
Could someone ever so kindly advice and show me what is incorrect in that function and what can be done to correct it so that it returns the correct value? I am obviously not seeing and/or understanding what is incorrect.
Thank you so very much for your help and time in advance!!!
#include <iostream>
#include <cstdlib>
int lastLargestIndex(int [], int);
int lastLowestIndex(int [], int );
using namespace std;
int main()
{
const int N = 15;
int arr[N] = {5,198,76,9,4,2,15,8,21,34,99,3,6,13,61};
int location;
//int location2;
location = lastLargestIndex( arr, N );
cout << "The last largest number is:" << location << endl;
location = lastLowestIndex(arr, N);
cout << "The last smallest number is:" << location << endl;
// std::system ("pause");
return 0;
}
int lastLargestIndex( int arr[], int size )
{
int highNum = 0;
for( int i = 0; i < size; i++ )
{
if ( arr[i] > highNum )
{
highNum = arr[i];
}
}
return highNum;
}
int lastLowestIndex(int arr[], int size)
{
int smallest = 0;
for (int i = 0; i < size; i++)
{
if (arr[i] < smallest)
{
smallest = arr[i];
}
}
//cout << smallest << '\n';
return smallest;
}
However, it is returning 0 all the time for function lastLowestIndex and I am unsure what I may be doing wrong.
You got a logic error when you initialised smallest to 0 in function lastLowestIndex() - that way if (arr[i] < smallest) condition is not evaluated to true if all input is positive. Instead, you should initialise it to the first member of array arr. The function should look like this:
int lastLowestIndex(int arr[], int size)
{
int smallest = arr[0];
for (int i = 0; i < size; i++)
{
if (arr[i] < smallest)
{
smallest = arr[i];
}
}
return smallest;
}
lastLowestIndex() initialises smallest to be 0, and then compares all elements of the array (which are positive, in your example) with it. All positive values are greater than zero, so smallest will remain zero.
Note that your logic is also not general for finding the maximum. Consider what the code will do if all elements of the array are negative.
You would be better off adopting a logic that does not make any assumptions about the array, other than its size and that it contains integral values. For example;
int lastLargestIndex( int arr[], int size )
{
int highNum = arr[0];
for( int i = 1; i < size; i++ )
{
if ( arr[i] > highNum )
{
highNum = arr[i];
}
}
return highNum;
}
This doesn't exhibit the problems yours does, since it initialises highNum with the first element of the array, and iterates over the rest (if any). This does assume size is positive.
Your functions are also named in a misleading manner, since they (attempt to) return the maximum (or minimum) value in the array, but their name suggests they will return the index of that value. I'll leave resolving that little issue as an exercise.
This is the correct working code!
#include <iostream>
#include <cstdlib>
int lastLargestIndex(int [], int);
int lastLowestIndex(int [], int );
using namespace std;
int main()
{
const int N = 15;
int arr[N] = {5,198,76,9,4,2,15,8,21,34,99,3,6,13,61};
int location;
location = lastLargestIndex( arr, N );
cout << "The last largest number is:" << location << endl;
location = lastLowestIndex(arr, N);
cout << "The last smallest number is:" << location << endl;
// std::system ("pause");
return 0;
}
int lastLargestIndex( int arr[], const int size )
{
int highNum = -100001;
for( int i = 0; i < size; i++ )
{
if ( arr[i] > highNum )
{
highNum = arr[i];
}
}
return highNum;
}
int lastLowestIndex(int arr[], const int size)
{
int smallest = 100001;
for (int i = 0; i < size; i++)
{
if (arr[i] < smallest)
{
smallest = arr[i];
}
}
//cout << smallest << '\n';
return smallest;
}
Modifications done:
Replaced argument in function from int size to const int size, since N is declared as const int in main function
Replaced highNum with -100001
Replaced smallest with 100001

Cannot convert parameter 1 from 'int' to 'int []'

For an assignment for my programming class, I am getting this error:
Error 1 error C2664: 'binarySearch' : cannot convert parameter 1 from 'int' to 'int []' Line 34.
#include<iostream>
using namespace std;
int selectionSort(int[], int);
int binarySearch(int[], int, int);
int sorted;
int main()
{
int size;
int i;
int desirednum;
cout << "How many values do you want to enter?";
cin >> size;
int* userarray = 0;
userarray = new int[size];
for (i = 0; i < size; i++)
{
cout << "Enter a value: ";
cin >> userarray[i];
}
int sorted = selectionSort(userarray, size);//calls the selection sort function
cout << "What value are you looking for: ";//asks what value they are searching for
cin >> desirednum;
int location = binarySearch(sorted, size, desirednum);
delete[] userarray;
return 0;
}
int selectionSort(int numbers[], int size)
{
int i, j, min, minidx, temp, desirednum, sorted = 0;
cout << "What value are you looking for: ";
cin >> desirednum;
for (i = 0; i < (size - 1); i++)
{
min = numbers[i];
minidx = i;
for (j = i + 1; j < size; j++)
{
if (numbers[j] < min)
{
min = numbers[j];
minidx = j;
}
}
if (min < numbers[i])
{
temp = numbers[i];
numbers[i] = min;
numbers[minidx] = temp;
sorted++;
}
}
return sorted;
}
int binarySearch(int& user_array, int amount, int value)
{
int left, right;
int* middle;
left = 0;
right = amount - 1;
while (left <= right)
{
middle = (int*)((left + right) / 2);
if (value == user_array[middle])
{
return *middle;
}
}
}
Your signature (the declaration) is
int binarySearch(int[], int, int);
But your definition is:
int binarySearch(int& user_array, int amount, int value)
This is not the same. The user_array is simply taking an int by reference. You want to take in an array (or a pointer).
As an aside, amount is rather misleading. size would be more accurate and typical.
Here's an example of the expected syntax and usage:
void printArray(int array[], int size) {
for(int i = 0; i < size; ++i) {
std::cout << array[i];
}
}
// Usage
int array[] = {1,2,3};
printArray(array, 3);
Note that the type of the parameter is int[] and not int& (which is merely a reference to an int). You can also use int*.
I haven't looked at C++ in a bit but I can tell in your call to your binarysearch() function, you are passing in a single int and not an integer array. You are passing in the variable "sorted" into binarysearch as the first parameter. "sorted" was declared as int and was assigned the return value of the selectionsort function. selectionsort() is defined with a return type of int.
I think the main problem is you should be passing in the variable "userarray" as the first parameter to binarysearch(). Look at the name if the first parameter to binarysearch().
The value being returned from selectionsort (sorted) appears to only be a counter keeping track of how many swaps had to occur in order to perform the selection sort. If you don't need that info (I don't see any use of that variable) then you could make the selectionsort a void function.
Edit - Also (thanks to Mike), I just noticed the differences in the function declaration vs. definition.

Can't find memory leak

I am learning C++ and my instructor has us going over dynamic memory allocation. In the below code it seems I have a memory leak because when I run the program I must about it at the end.
In the output I get everything is correct except for the Data: field which should list all the numbers in the array, but instead gives me some -3435893 jibberish.
Lowest: also does this. After the program displays everything I get a memory error that memory is being written to after end of heap buffer.
I'm new to all this but I'm guessing the problem is when arrPTR[0] is accessed just because I get the same problem for Lowest: and not Highest:. I don't know for sure but I would appreciate any help I can get.
#include <iostream>
using namespace std;
int* readArray(int&);
void sortArray(int *, const int * );
int findMode(int*, const int *);
double averageNumber(int*,const int*);
void lowestHighest(int*,const int*,int&,int&);
void printFunc(int*,const int*, int, int, double);
int main ()
{
int size = 0;
int *arrPTR = readArray(size);
const int *sizePTR = &size;
sortArray(arrPTR, sizePTR);
int mode = findMode(arrPTR,sizePTR);
double average = averageNumber(arrPTR, sizePTR);
int lowest = 0, highest = 0;
lowestHighest(arrPTR,sizePTR,lowest,highest);
printFunc(arrPTR,sizePTR,lowest,highest,average);
delete [] arrPTR;
system("pause");
return 0;
}
int* readArray(int &size)
{
cout<<"Enter a number for size of array.\n";
cin>>size;
int *arrPTR = new int[size];
for(int count = 0; count < size; count++)
{
cout<<"Enter positive numbers to completely fill the array.\n";
cin>>arrPTR[count];
}
return arrPTR;
}
void sortArray(int *arrPTR, const int *sizePTR)
{
int temp;
bool swap;
do
{
swap = false;
for(int count = 0; count < *sizePTR; count++)
{
if(arrPTR[count] > arrPTR[count+1])
{
temp = arrPTR[count];
arrPTR[count] = arrPTR[count+1];
arrPTR[count+1] = temp;
swap = true;
}
}
} while (swap);
}
int findMode(int *arrPTR, const int *sizePTR)
{
int most_found_element = arrPTR[0];
int most_found_element_count = 0;
int current_element = arrPTR[0];
int current_element_count = 0;
int count;
for (count = 0; count < *sizePTR; count++)
{
if(count == arrPTR[count])
current_element_count++;
else if(current_element_count > most_found_element)
{
most_found_element = current_element;
most_found_element_count = current_element_count;
}
current_element = count;
current_element_count=1;
}
return most_found_element;
}
double averageNumber(int *arrPTR,const int *sizePTR)
{
double total = 0;
for (int count = 0; count > *sizePTR; count++)
total+=arrPTR[count];
double average = total / *sizePTR;
return average;
}
void lowestHighest(int *arrPTR, const int *sizePTR,int &lowest, int &highest)
{
//Since array is already sorted the lowest number will be in the lowest element and the highest will be in the highest element.
lowest = arrPTR[0];
highest = arrPTR[*sizePTR-1];
}
void printFunc(int *arrPTR, const int *sizePTR, int lowest, int highest, double average)
{
cout<<"Array Stats\n";
cout<<"Data:";
for(int count = 0; count < *sizePTR; count++)
cout<<arrPTR[count];
cout<<"\n";
cout<<"Mode:"<<endl;
cout<<"Average:"<<average<<endl;
cout<<"Low Value:"<<lowest<<endl;
cout<<"High Value:"<<highest<<endl;
}
The first thing I spot is that in sortArray you access element count + 1 which can be one-past the end of your array. After that, all other bets about your program behavior are off.