I am new to C ++, and now there is one thing I want to clarify. When I look through the tutorial, there is this program that stores user input in an array and gives the sum of all numbers when the user exits the program:
int readArray(int integerArray[], int maxNumElements);
int sumArray(int integerArray[], int numElements);
void displayArray(int integerArray[], int numElements);
int main(int nNumberofArgs, char* pszArgs[])
{
cout << "This program sums values entered\n";
cout << "Terminate the loop by entering a negative number" << endl;
int inputValues [128];
int numberOfValues = readArray(inputValues, 128);
displayArray(inputValues, numberOfValues);
cout << "The sum is " << sumArray(inputValues, numberOfValues) << endl;
return 0;
}
int readArray(int integerArray[], int maxNumElements)
{
int numberOfValues;
for(numberOfValues = 0; numberOfValues < maxNumElements; numberOfValues++)
{
int integerValue;
cout << "Enter next number: ";
cin >> integerValue;
if (integerValue < 0)
{
break;
}
integerArray[numberOfValues] = integerValue;
}
return numberOfValues;
}
void displayArray(int integerArray[], int numElements)
{
cout << "The value of the array is:" << endl;
for(int i = 0; i < numElements; i++)
{
cout << i << ":" << integerArray[i] << endl;
}
cout << endl;
}
int sumArray(int integerArray[], int numElements)
{
int accumulator = 0;
for(int i = 0; i < numElements; i++)
{
accumulator += integerArray[i];
}
return accumulator;
}
My questions:
- Is it necessary to declare local variables in each function (e.g.
int inputValues [128];)? - Would it be correct to store the input in the arguments that were declared in the function prototype? For example, is it possible to just save everything in
integerArray[]instead of creating a storage array integerValue?
This may seem obvious, but I want to understand this in order to avoid mistakes in the future.