Here is a sample design for a function named Average which uses an array numList of type ListType. The C++ code follows the design.
The DESIGN:
Function: Average
PreCond: numList contains numNums integers to be averaged
PostCond: the average of the integers in numList has
been returned
Data passed in: numList
ListType Array of integers
numNums integer Number
of items in array to be averaged
Data passed out: None
Returns: (Decimal) average of the integers in numList
Local variables:
ctr
integer For loop counter
sum
integer sum of numbers
to be averaged
Algorithm: (pseudocode)
Note: you could have used a while loop to sum the
integers. If you did, you'd have to initialize the counter and show
the step where it gets incremented each time in the loop. For this
reason, the for loop seems a lot simpler to use.
// The C++ code:
// (function) Average
// PreCond: numList contains numNums integers
// PostCond: the average of the integers has been
returned
//===============================================
float Average (ListType numList, int numNums)
{
int
sum = 0; // accumulator for sum
// add up the
numbers in the list
for (int ctr=0;
ctr < numNums; ctr++)
sum = sum + numList[ctr];
// return the
average
return (float(sum)/numNums);
}