UMBC CS 201, Fall 02
UMBC CMSC 201 Fall '02 CSEE | 201 | 201 F'02 | lectures | news | help

One-dimensional Arrays as Parameters

Our story continues

So Mr. Bill and the programmers opened their copies of K & R and discovered that they can pass the entire array to a function as a single parameter. So, they changed their function prototype to have just two parameters -- the name of the array (followed by empty brackets) and the number of elements in the array. int AddSales (int sales[ ], int nrElements ); and changed the function call to reflect these changes totalSales = AddSales (sales, NRDAYS); and changed the code for the function to use a loop and add all the elements.

And the result was the following program.

/****************************** ** File: array1.c ** Author: D. Frey ** Date: 2/7/00 ** Section: 203 ** SSN: 123-45-6789 ** EMail: frey@cs.umbc.edu ** ** This file shows how to pass an array ** to a function. ** ******************************/ #include <stdio.h> #define NRDAYS 5 /* number of business days */ int AddSales (int sales[ ], int nrElements); int main ( ) { /* sales for each business day */ int sales[NRDAYS] = {288, 359, 509, 777, 1044}; int totalSales; int day; /* print each days sales */ printf ("\n"); for (day = 0; day < NRDAYS; day++) { printf ("Sales for day %d: %d\n", day + 1, sales[day]); } /* get and print the total sales */ totalSales = AddSales (sales, NRDAYS); printf ("\nTotal Sales: %d\n", totalSales); return 0; } /****************************** ** Function: AddSales ** ** Inputs: an array of sales ** number of days in the array ** Output: returns the total sales ********************************/ int AddSales (int sales[ ], int nrElements) { int total = 0; int i; for (i = 0; i < nrElements; i++) { total += sales[i]; } return total; } And so it was the Mr. Bill and the programmers made Bob a happy man and all got big raises and an extra week's vacation.

But....

Little did Mr. Bill know that there was much more to come... Mr. Bill was about to discover the true power of passing arrays to functions.
Last Modified - Friday, 23-Aug-2002 11:05:02 EDT


CSEE | 201 | 201 F'02 | lectures | news | help