Hi so I am having trouble passing through my array into Functions. The functions would be the sum, average, min and max of the array.. this what I have so far...
There is no ambiguity here:
Using the unqualified name array at block scope would refer to the name array declared at block scope (in main)
It hides the name array (ie. std::array) declared at namespace scope.
Arrays are not copy assignable objects. To pass an array to a function, we have two options:
a. pass the array by reference (size known at compile-time)
b. pass a pointer to the first element of the array, and also the size of the array.
#include <iostream>
usingnamespace std;
constint ARRAY_SZ = 5 ;
// a covenient alias for the type: 'array of ARRAY_SZ int'
using array_type = int[ARRAY_SZ] ;
// option one: pass the array by reference
longlong sum( const array_type& array )
{
longlong s = 0 ;
// range-based loop see: http://www.stroustrup.com/C++11FAQ.html#forfor( int v : array ) s += v ;
return s ;
}
// option two: pass a pointer to the first element of the array and the size of the array
int min( constint array[], int array_size ) // invariant: num_items > 0
{
int min_val = array[0] ;
// iterate through items starting at position 1
for( int i = 1 ; i < array_size ; ++i )
if( array[i] < min_val ) min_val = array[i] ;
return min_val ;
}
int main()
{
int array[ARRAY_SZ ]; // or equivalently: array_type array ;
cout << "Welcome to the World of Arrays!!!!!" << endl;
for (int i = 0; i < ARRAY_SZ ; ++i )
{
cout << "Enter element " << i + 1 << "\t";
cin >> array[i];
}
cout << "You have entered: " << "\n";
cout << "Position Value" << "\n";
cout << "-------------------" << endl;
// Array Displayed in List
for (int i = 0; i < ARRAY_SZ ; ++i )
{
cout << i << " \t\t" << array[i] << endl;
}
// pass the array by reference
std::cout << "the sum is: " << sum(array) << '\n' ;
// pass a pointer to the first element and number of elements
// see Array-to-pointer decay: http://en.cppreference.com/w/cpp/language/array
std::cout << "the minimum value is: " << min( array, ARRAY_SZ ) << '\n' ;
cin.get();
}