Fall '06

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

Why should we pass arrays to functions?

An example

Bob owns a sporting good store which is open for 5 days during the week (Monday - Friday). His programming staff has written a small program to show Bob how easy it is to calculate total sales for the week. /****************************** ** File: elements.c ** Author: D. Frey ** Date: 2/7/00 ** Section: 203 ** EMail: ** ** This file is an example of passing each element ** of an array to a function. It provides the ** rationale for being able to pass the entire array ** ******************************/ #include <stdio.h> #define NRDAYS 5 /* number of business days */ int AddSales (int sales1, int sales2, int sales3, int sales4, int sales5); 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[0], sales[1], sales[2], sales[3], sales[4]); printf ("\nTotal Sales: %d\n", totalSales); return 0; } /****************************** ** Function: AddSales ** ** Inputs: sales amounts for 5 days ** Output: returns the total sales ********************************/ int AddSales (int s1, int s2, int s3, int s4, int s5) { int total = 0; total += s1; total += s2; total += s3; total += s4; total += s5; return total; } The output from the program was 1inux1[104] % a.out Sales for day 1: 288 Sales for day 2: 359 Sales for day 3: 509 Sales for day 4: 777 Sales for day 5: 1044 Total Sales: 2977 linux1[105] %

But There's a Problem

Being an astute business man, Bob noticed that the sales were increasing each day. He decided that he would open his store on Saturday and Sunday too and told his programmers to modify their program to handle it.

In typical programmer fashion they said, "Not a problem. All we have to do is modify the AddSales function. We have to add 2 more parameters and two more lines of code."

And as they were adding the code, Ben, the lead programmer said, "Hey what if Bob wants to calculate the sales for entire month instead of just one week. Can your program handle that too?"

And the programmers exclaimed, "OH, @!#*! What can we do now?"

And Ben calmly replied, "Don't worry.. we can fix it."

And so Ben and the programmers learned that they didn't have to pass each element of an array to a function as individual parameters.

There was a better way.

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