Hi, so basically this program just takes an array of user input and sorts the numbers in ascending order, then it passes this array to a function that will display the average of this array. It is a very small array, but I am running into an error in the average function if someone could assist here that would be great. I feel like I am so close to finishing this.
#include <iostream>
#include <string>
#include <iomanip>
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::fixed;
using std::setprecision;
void sortArray();
void displayAverage(int []);
int main()
{
cout << "Hi there, I will be taking whatever numbers you give me and I will sort them in ascending order and also give you the average!" << endl << endl;
sortArray();
return 0;
} //end of main function
//start of sort function
void sortArray()
{
int num[5] = {0, 0, 0, 0, 0};
int x = 0; //keeps track of subscripts
int temp = 0; //variable used for swapping
int maxSub = 4; //maximum subscript
int lastSwap = 0; //indicates position of last swap
char swap = 'Y'; //indicates whether a swap was made
//take input for num[x]
cout << "Please enter your first number: ";
cin >> num[0];
cout << endl;
for (int x = 1; x < 5; x = x + 1)
{
cout << "Next number: ";
cin >> num[x];
}
//keep repeating as long as swaps are made
while (swap == 'Y')
{
swap = 'N'; //assume no swap is neccessary
x = 0; //begin comparing the first array element
//compare adjacent array elements to determine whether a swap is needed
while (x < maxSub)
{
if (num[x] > num[x + 1])
{
//a swap is needed
temp = num[x];
num[x] = num[x + 1];
num[x + 1] = temp;
swap = 'Y';
lastSwap = x;
} //endif
x += 1; //increment subscript
} //endwhile
maxSub = lastSwap; //reset max subscript
} //endwhile
//display sorted array
for (int x = 0; x < 4; x = x + 1)
cout << num[x] << endl;
//end for
//pass array on to get average
displayAverage(num);
} //end of sort function
void displayAverage(int numbers)
{
int total = 0;
double average = 0;
//Gets total
for (int x = 0; x < 5; x += 1)
total = total + numbers[x];
//end for
//calculates and displays average
average = static_cast<double>(total) / 5.0;
cout << "Average: " << average << endl;
} //end of average function
A pointer is a fundamental data type in C++. Definitely read up on them.
See this function; void displayAverage(int numbers) ? It accepts an object of type int, named numbers.
See this function call; displayAverage(num); ? You're passing in num, which is a pointer to an int.
The function accepts an int. You are passing a pointer to an int. num is an array; when you pass an array like that, you're passing a pointer. If you passed num[1] you would be passing an int.
When a function accepts one type as an input parameter, you cannot just try to pass it something else. Sometimes the compiler will make a guess as to what you meant and try to convert it for you; sometimes it will simply give up. In this case, it's giving up.