Hi cplusplus.com forum. Could someone help me build this code into anything simple so that it works please.
#include <iostream>
using namespace std;
int main()
{
void fillUp(int a[], int size);
// Precondition: size is the declared size of the array a.
// The user will type in size integers.
// Postcondition: The array a is filled with size integers
// from the keyboard.
void fillUp(int a[], int size)
{
cout << "Enter " << size << " numbers:\n";
for (int i = 0; i < size; i++)
cin >> a[i];
cout << "The last array index used is " << (size - 1) << endl;
}
}
I would separate the code that provides entering of the array size and the code that provides filling of the array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
int get_size()
{
std::cout << "Enter array size: ";
int n;
if ( ! ( std::cin >> n ) ) n = 0;
return ( n );
}
int * create_array( int n )
{
int *a = new intw[n];
std::cout << "Enter " << n << " integer numbers: ";
for ( intint i = 0; i < n; i++ ) std::cin >> a[i];
return ( a );
}
and in the main they used the following way
1 2 3
int *a = create_array( get_size() );
delete [] a;
However as your array is declared in main then your code will look
#include <iostream>
usingnamespace std;
void fillUp( int a[], int size );
int main()
{
constint N = 10;
int a[N];
fillUp( a, N );
return 0;
}
// Precondition: size is the declared size of the array a.
// The user will type in size integers.
// Postcondition: The array a is filled with size integers
// from the keyboard.
void fillUp( int a[], int size )
{
cout << "Enter " << size << " numbers:\n";
for (int i = 0; i < size; i++) cin >> a[i];
cout << "The last array index used is " << (size - 1) << endl;
}