You are on page 1of 18

Functions with Output Parameters

So far, we know how to pass inputs to a function and how to use the return statement to send back one result value from a function. But programmers use output parameters also to return multiple results from a function. When a function call executes, the computer allocates memory space in the function data area for each formal parameter. The value of each actual parameter is stored in the memory cell allocated to its corresponding formal parameter. Or, we can use the address of operator ( & ) to store the actual parameters address instead of its value. Next, how a function uses pointers and the indirection operator ( * ) to return results to the function that calls it.

The actual argument value passed to the formal parameter num is used to determine . Notice that in Fig. 6.3 the declarations of these output parameters in the function heading have asterisks before the parameter names denoting that they are pointers. The assignment statements in the function use indirect reference to send back the function results. The function type is void as it is for functions returning no result, and the function body does not include a return statement to send back a single value, as we saw in earlier functions. The declaration char *signp tells the compiler that output parameter signp will contain the address of a type char variable. Another way to express the idea that signp is the address of a type char variable is to say that the parameter signp is a pointer to a type char variable. Similarly, the output parameters wholep and fracp are pointers to variables of types int and double . We have chosen names for these output parameters that end in the letter p because they are all pointers. 1. /* 2. * Demonstrates the use of a function with input and output parameters. 3. */ 4. 5. #include <stdio.h> 6. #include <math.h> 7. void separate(double num, char *signp, int *wholep, double *fracp); 8. 9. int

10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57.

main(void) { double value; /* input - number to analyze */ char sn; /* output - sign of value */ int whl; /* output - whole number magnitude of value */ double fr; /* output - fractional part of value */ /* Gets data */ printf("Enter a value to analyze> "); scanf("%lf", &value); /* Separates data value into three parts */ separate(value, &sn, &whl, &fr); /* Prints results */ printf("Parts of %.4f\n sign: %c\n", value, sn); printf(" whole number magnitude: %d\n", whl); printf(" fractional part: %.4f\n", fr); return (0); } /* * Separates a number into three parts: a sign (+, -, or blank), * a whole number magnitude, and a fractional part. * Pre: num is defined; signp, wholep, and fracp contain addresses of memory * cells where results are to be stored * Post: function results are stored in cells pointed to by signp, wholep, and * fracp */ void separate(double num, /* input - value to be split */ char *signp, /* output - sign of num */ int *wholep, /* output - whole number magnitude of num */ double *fracp) /* output - fractional part of num */ { double magnitude; /* local variable - magnitude of num */ /* Determines sign of num */ if (num < 0) *signp = '-'; else if (num == 0) *signp = ' '; else *signp = '+'; /* Finds magnitude of num (its absolute value) and separates it into whole and fractional parts */ magnitude = fabs(num);

58. *wholep = floor(magnitude); 59. *fracp = magnitude - *wholep; 60. } Enter a value to analyze> 35.817 Parts of 35.8170 sign: + whole number magnitude: 35 fractional part: 0.8170

Multiple Calls to a Function with Input/Output Parameters In previous examples, we passed information into a function through its input parameters and returned results from a function through its output parameters. Our next example demonstrates the use of a single parameter both to bring a data value into a function and to carry a result value out of the function. It also demonstrates how a function may be called more than once in a given program and process different data in each call. Program to Sort Three Numbers 1. /* 2. * Tests function order by ordering three numbers 3. */ 4. #include <stdio.h> 5. 6. void order(double *smp, double *lgp);

7. 8. int 9. main(void) 10. { 11. double num1, num2, num3; /* three numbers to put in order */ 12. 13. /* Gets test data */ 14. printf("Enter three numbers separated by blanks> "); 15. scanf("%lf%lf%lf", &num1, &num2, &num3); 16. 17. /* Orders the three numbers */ 18. order(&num1, &num2); 19. order(&num1, &num3); 20. order(&num2, &num3); 21. 22. /* Displays results */ 23. printf("The numbers in ascending order are: %.2f %.2f %.2f\n", 24. num1, num2, num3); 25. 26. return (0); 27. } 28. 29. /* 30. * Arranges arguments in ascending order. 31. * Pre: smp and lgp are addresses of defined type double variables 32. * Post: variable pointed to by smp contains the smaller of the type 33. * double values; variable pointed to by lgp contains the larger 34. */ 35. void 36. order(double *smp, double *lgp) /* input/output */ 37. { 38. double temp; /* temporary variable to hold one number during swap */ 39. /* Compares values pointed to by smp and lgp and switches if necessary */ 40. if (*smp > *lgp) { 41. temp = *smp; 42. 43. *smp = *lgp; 44. *lgp = temp; 45. } 46. }

Output: Enter three numbers separated by blanks> 7.5 9.6 5.5 The numbers in ascending order are: 5.50 7.50 9.60

identifies smp and lgp as input/output parameters because the function uses the current actual argument values as inputs and may return new values. During the execution of the second call order(&num1, &num3); the formal parameter smp contains the address of the actual argument num1 , and the formal parameter lgp contains the address of the actual argument num3 . Testing thecondition (*smp > *lgp) causes both of these pointers to be followed, resulting in the condition (7.5 > 5.5) which evaluates to true. Executing the first assignment statement in the true task, temp = *smp; causes the 7.5 to be copied into the local variable temp . Figure 6.8 shows us a snapshot of the values in memory immediately after execution of this assignment statement. Execution of the next assignment statement, *smp = *lgp; would cause the 7.5 in the variable pointed to by smp to be replaced by 5.5 , the value of the variable pointed to by lgp . The final assignment statement, *lgp = temp; copies the contents of the temporary variable ( 7.5 ) into the variable pointed to by lgp . This completes the swap of values.

A scope in any programming is a region of the program where a defined variable can have its existence and beyond that variable can not be accessed. There are three places where variables can be declared in C programming language: 1. Inside a function or a block which is called local variables, 2. Outside of all functions which is called global variables. 3. In the definition of function parameters which is called formal parameters. Let us explain what are local and global variables and formal parameters. Local Variables Variables that are declared inside a function or block are called local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own. Following is the example using local variables. Here all the variables a, b and c are local to main() function.

#include <stdio.h> int main () { /* local variable declaration */ int a, b; int c; /* actual initialization */ a = 10; b = 20; c = a + b; printf ("value of a = %d, b = %d and c = %d\n", a, b, c); return 0; } Global Variables Global variables are defined outside of a function, usually on top of the program. The global variables will hold their value throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program. A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. Following is the example using global and local variables:

#include <stdio.h> /* global variable declaration */ int g; int main () { /* local variable declaration */ int a, b; /* actual initialization */ a = 10; b = 20; g = a + b; printf ("value of a = %d, b = %d and g = %d\n", a, b, g); return 0; } A program can have same name for local and global variables but value of local variable inside a function will take preference. Following is an example: #include <stdio.h> /* global variable declaration */ int g = 20; int main () { /* local variable declaration */ int g = 10; printf ("value of g = %d\n", g); return 0; } When the above code is compiled and executed, it produces the following result: value of g = 10 Formal Parameters Function parameters, formal parameters, are treated as local variables with-in that function and they will take preference over the global variables. Following is an example:

#include <stdio.h> /* global variable declaration */ int a = 20; int main () { /* local variable declaration in main function */ int a = 10; int b = 20; int c = 0; printf ("value of a in main() = %d\n", a); c = sum( a, b); printf ("value of c in main() = %d\n", c); } return 0;

/* function to add two integers */ int sum(int a, int b) { printf ("value of a in sum() = %d\n", a); printf ("value of b in sum() = %d\n", b); } return a + b;

When the above code is compiled and executed, it produces the following result: value value value value of of of of a in main() = 10 a in sum() = 10 b in sum() = 20 c in main() = 30

Initializing Local and Global Variables When a local variable is defined, it is not initialized by the system, you must initialize it yourself. Global variables are initialized automatically by the system when you define them as follows: Data Type int char float Initial Default Value 0 '\0' 0

double pointer

0 NULL

Array Subscripts:
Understanding the distinction between an array subscript value and an array element value is essential. The subscripted variable x[i] references a particular element of this array. If i has the value 0 ,the subscript value is 0 , and x[0] is referenced. The value of x[0] in this case is 16.0 . If i has the value 2 , the subscript value is 2 , and the value of x[i] is 6.0 . If i has the value 8 , the subscript value is 8 , and we cannot predict the value of x[i] because the subscript value is out of the allowable range.

Using for Loops for Sequential Access


Assume that the name SIZE has been defined to be 11 . int square[SIZE], i; The for loop for (i = 0; i < SIZE; ++i) square[i] = i * i;

1. /* 2. * Computes the mean and standard deviation of an array of data and displays 3. * the difference between each value and the mean. 4. */ 5. 6. #include <stdio.h> 7. #include <math.h> 8. 9. #define MAX_ITEM 8 /* maximum number of items in list of data */ 10. 11. int 12. main(void) 13. { 14. double x[MAX_ITEM], /* data list */

15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47.

mean, /* mean (average) of the data */ st_dev, /* standard deviation of the data */ sum, /* sum of the data */ sum_sqr; /* sum of the squares of the data */ int i; /* Gets the data */ printf("Enter %d numbers separated by blanks or <return>s\n> ", MAX_ITEM); for (i = 0; i < MAX_ITEM; ++i) scanf("%lf", &x[i]); /* Computes the sum and the sum of the squares of all data */ sum = 0; sum_sqr = 0; for (i = 0; i < MAX_ITEM; ++i) { sum += x[i]; sum_sqr += x[i] * x[i]; } /* Computes and prints the mean and standard deviation */ mean = sum / MAX_ITEM; st_dev = sqrt(sum_sqr / MAX_ITEM - mean * mean); printf("The mean is %.2f.\n", mean); printf("The standard deviation is %.2f.\n", st_dev); /* Displays the difference between each item and the mean */ printf("\nTable of differences between data values and mean\n"); printf("Index Item Difference\n"); for (i = 0; i < MAX_ITEM; ++i) printf("%3d%4c%9.2f%5c%9.2f\n", i, ' ', x[i], ' ', x[i] - mean); return (0); }

Enter 8 numbers separated by blanks or <return>s > 16 12 6 8 2.5 12 14 -54.5 The mean is 2.00. The standard deviation is 21.75. Table of differences between data values and mean Index Item Difference 0 16.00 14.00 1 12.00 10.00 2 6.00 4.00 3 8.00 6.00 4 2.50 0.50 5 12.00 10.00 6 14.00 12.00

-54.50

-56.50

The program uses three for loops to process the array x . The constant MAX_ITEM determines the size of the array. The variable i is used as the loop control variable and array subscript in each loop. The first for loop, for (i = 0; i < MAX_ITEM; ++i) scanf("%lf", &x[i]); stores one input value into each element of array x (the first item is placed in x[0] , the next in x[1] , and so on). The call to scanf is repeated for each value of i from 0 to 7 ; each repetition gets a new data value and stores it in x[i] . The subscript I determines which array element receives the next data value.

Using Array Elements as Function Arguments:


uses array element x[i] as an input argument to function printf . When i is 3 , the value of x[3] or 8.0 is passed to printf and displayed. Printf(- - - - - - - - - - -,x[i]); uses array element x[i] as an output argument of scanf . When i is 4 , the address of array element x[4] is passed to scanf , and scanf stores the next value scanned ( 2.5 ) in element x[4] . scanf("%lf",&x[i]);

You can also pass array elements as arguments to functions that you write. Each array element must correspond to a formal parameter that is the same simple type as the array element. The function prototype below shows one type double input parameter ( arg_1 ) and two type double * output parameters ( arg2_p and arg3_p ). void do_it (double arg_1, double *arg2_p, double *arg3_p); If p , q , and r are declared as type double variables in the calling module, the statement do_it (p, &q, &r); passes the value of p to function do_it and returns the function results to variables q and r . If x is declared as an array of type double elements in the calling module, the statement do_it(x[0], &x[1], &x[2]); uses the first three elements of array x as actual arguments. Array element x[0] is an input argument and x[1] and x[2] are output arguments (see Fig. 7.3 ). In function do_it , you can use statements like *arg2_p = ... *arg3_p = ...

Array Arguments: Besides passing individual array elements to functions, we can write functions that have arrays as arguments. Such functions can manipulate some, or all, of the elements corresponding to an actual array argument.

Formal Array Parameters When an array name with no subscript appears in the argument list of a function call, what is actually stored in the functions corresponding formal parameter is the address of the initial array element. In the function body, we can use subscripts with the formal parameter to access the arrays elements. However, the function manipulates the original array, not its own personal copy, so an assignment to one of the array elements by a statement in the function changes the contents of the original array.

In function fill_array , the array parameter is declared as int list[] Notice that the parameter declaration does not indicate how many elements are in list . Because C does not allocate space in memory for a copy of the actual array, the compiler does not need to know the size of the array parameter. In fact, since we do not provide the size, we have the flexibility to pass to the function an array of any number of integers.

Argument Correspondence for Array Parameters


To call function fill_array , you must specify the actual array argument, the number of array elements, and the value to be stored in the array. If y is an array with ten type int elements, the function call fill_array(y, 10, num); stores the value of num in the ten elements of array y . If x is a five-element array of type int values, the statement fill_array(x, 5, 1); causes function fill_array to store 1 in all elements of array x . Figure 7.5 shows the data areas just before the return from the function call fill_array(x, 5, 1);

Use of *list Instead of list[] in a Formal Parameter List In the declaration for function fill_array , we can use either parameter declaration: int list[] int *list`

Arrays as Input Arguments:

Returning an Array Result

The formal parameter list declaration const double ar1[], const double ar2[], double arsum[], int n indicates that formal parameters ar1 , ar2 , and arsum stand for actual argument arrays whose elements are of type double and that ar1 and ar2 are strictly input parameters, as is n . The function can process type double arrays of any size as long as the preconditions stated in the initial block comment are met. If we assume that a calling function has declared three five-element arrays x , y , and x_plus_y and has filled x and y with data, the call add_arrays(x, y, x_plus_y, 5); would lead to the memory setup pictured in Fig. 7.9 . After execution of the function, x_plus_y[0] will contain the sum of x[0] and y[0] , or 3.5 ; x_plus_y[1] will contain the sum of x[1] and y[1] , or 6.7 ; and so on. Input argument arrays x and y will be unchanged; output argument array x_plus_y will have these new contents:

Searching and Sorting an Array:

Lab Manual programs are the examples of search and sort


. TWO DIMENSIONAL ARRAYS An array of arrays is called a two-dimensional array and can be regarded as a table with a number of rows and columns:

'J' 'o' 'h' 'n' 'M' 'a' 'r' 'y' 'I' 'v' 'a' 'n'

is a 3 4 array: 3 rows, 4 columns

'J' 'o' 'h' 'n' 'M' 'a' 'r' 'y' 'I' 'v' 'a' 'n'

This is an array of size 3 names [3] whose elements are arrays of size 4 [4] whose elements are characters char

DECLARATION OF TWO DIMENSIONAL ARRAY

The above figure shows the representation of elements in the two-dimensional array Example, char names[3][4];

in the above declaration char(elementType) specifies type of element in each slot

names(arrayName) specifies name of the array [3](rows) [4](cols) specifies number of rows specifies number of columns

INITIALIZATION OF TWO DIMENSIONAL ARRAYS An array may be initialized at the time of declaration:

char names [3][4] = { {J, 'o', 'h', 'n'}, {M, 'a', 'r', 'y'}, {I, 'v', 'a', 'n'} };
An integer array may be initialized to all zeros as follows

int nums [3][4] = {0};


In the declaration of two dimensional array the column size should be specifed, to that it can arrange the elements in the form of rows and columns. Two-dimensional arrays in C are stored in "row-major format": the array is laid out contiguously, one row at a time: To access an element of a 2D array, you need to specify both the row and the column:

nums[0][0] = 16; printf ("%d", nums[1][2]);


MULTI DIMENSIONAL ARRAYS C allows three or more dimensions. The exact limit is determined by the compile. The general form of multidimensional array is

type arrayName[s1][s2][s3].[sm];
Where si is the size of the ith dimension. Array declarations read right-to-left For example

int a[10][3][2];
it is represented as an array of ten arrays of three arrays of two ints In memory the elements are stored as shown in below figure

You might also like