UMBC CMSC 201 Fall '05
CSEE | 201 | 201 F'05 | lectures | news | help

One-dimensional Arrays as Parameters

Our story continues

So Ben 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
 ** 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
 **
 ** This function totals the sales for
 ** all of the days' sales in the array
 **
 ** 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 that Ben and the programmers made Bob a happy man and all got big raises and an extra week's vacation.

But....

Little did Ben know that there was much more to come... Ben was about to discover the true power of passing arrays to functions.

Last Modified - Wednesday, 05-Oct-2005 12:30:30 EDT


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