For these examples we pass Arrays as pointers to arrays. I also separate the function prototypes, the actual function definitions and the main into three files. The prototypes are put in a header file. the actual definitions are stored in a .cpp file, as is the main() function.
Both the function definitions and the main must have an include statement that includes the header file.
Here is the main file.
#include <iostream>
#include "ArrayFunction.h"
using namespace std;
int main()
{
CreateArray();
char c;
cin >> c;
}
Notice how simple and clean it is. It only calls the starting function. Here is the
header file:
ArrayFunction.h
void CreateArray();
void FillArray(int * arr, int size);
void DisplayArray(const int * arr, int size);
int SumArray(const int * arr, int size);
A couple of notes on the function prototypes. Notice we are passing pointers to an array called "arr." Whenever you pass an array as an argument you are in fact passing an pointer. This format just makes it explicit.
Also note the use the "const" keyword. It protects the array from being changed by the function it is passed to. I didn't do it for the FillArray() function because it needs to change the array.
Here is the file that has the actual function definitions:
FunctionArrays.cpp
#include <iostream>
#include "ArrayFunction.h"
#include <cmath>
#include <ctime>
using namespace std;
void CreateArray()
{
int arr[10];
FillArray(arr,10);
}
void FillArray(int * arr, int size)
{
srand(time(0));
for(int i=0;i<size;i++)
{
int number = rand();
arr[i]=number;
}
DisplayArray(arr, size);
}
int SumArray(const int * arr, int size)
{
int total=0;
for(int i=0;i<size;i++)
{
total += arr[i];
}
return total;
}
void DisplayArray(const int *arr, int size)
{
for (int i=0;i<size;i++)
{
cout << arr[i]<<endl;
}
cout << "\n\nthe total is: "<< SumArray(arr, size) << endl;
}
This kind of separation of prototype from definition adds to clarity and re-usability of the code. We will see more of this when we do classes.
No comments:
Post a Comment