Extention of Unit 4

Embed Size (px)

Citation preview

  • 8/13/2019 Extention of Unit 4

    1/18

    Functions with Output ParametersSo far, we know how to pass inputs to a function and how to use the returnstatement to send backone result value from a function. But programmers use output parameters also toreturn multiple results from a function.

    When a function call executes, the computer allocates memory space in thefunction data area for each formal parameter. The value of each actual parameter isstored in the memory cell allocated to its corresponding formal parameter. Or, wecan use the address of operator ( & ) to store the actual parameters addressinstead of its value.Next, how a function uses pointers and the indirection operator ( * ) to returnresults to the function that calls it.

    The actual argument value passed to the formal parameter num is used todetermine . Notice that in Fig. 6.3 the declarations of these output parameters inthe function heading have asterisks before the parameter names denoting that they

    are pointers. The assignment statements in the function use indirect reference tosend back the function results. The function type is void as it is for functionsreturning no result, and the function body does not include a return statement tosend 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 atype char variable. Another way to express the idea that signp is the address of atype char variable is to say that the parameter signp is a pointer to a type charvariable. Similarly, the output parameters wholep and fracp are pointers tovariables of types int and double . We have chosen names for these outputparameters 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 6. #include 7. void separate(double num, char *signp, int *wholep, double *fracp);8.9. int

  • 8/13/2019 Extention of Unit 4

    2/18

    10. main(void)11. {12. double value; /* input - number to analyze */13. char sn; /* output - sign of value */14. int whl; /* output - whole number magnitude of value */15. double fr; /* output - fractional part of value */16.17./* Gets data */18. printf("Enter a value to analyze> ");19. scanf("%lf", &value);20.21./* Separates data value into three parts */22. separate(value, &sn, &whl, &fr);23.24./* Prints results */25. printf("Parts of %.4f\n sign: %c\n", value, sn);26. printf(" whole number magnitude: %d\n", whl);

    27. printf(" fractional part: %.4f\n", fr);28.29. return (0);30. }31.32./*33. * Separates a number into three parts: a sign (+, -, or blank),34. * a whole number magnitude, and a fractional part.35. * Pre: num is defined; signp, wholep, and fracp contain addresses of memory36. * cells where results are to be stored37. * Post: function results are stored in cells pointed to by signp, wholep, and

    38. * fracp39. */40. void41. separate(double num, /* input - value to be split */42. char *signp, /* output - sign of num */43. int *wholep, /* output - whole number magnitude of num */44. double *fracp) /* output - fractional part of num */45. {46. double magnitude; /* local variable - magnitude of num */47./* Determines sign of num */48. if (num < 0)49. *signp = '-';

    50. else if (num == 0)51. *signp = ' ';52. else53. *signp = '+';54.55./* Finds magnitude of num (its absolute value) and separates it into56. whole and fractional parts */57. magnitude = fabs(num);

  • 8/13/2019 Extention of Unit 4

    3/18

    58. *wholep = floor(magnitude);59. *fracp = magnitude - *wholep;60. }

    Enter a value to analyze> 35.817Parts of 35.8170sign: +whole number magnitude: 35fractional part: 0.8170

    Multiple Calls to a Function with Input/Output ParametersIn previous examples, we passed information into a function through its inputparameters and returned results from a function through its output parameters.Our next example demonstrates the use of a single parameter both to bring a datavalue into a function and to carry a result value out of the function. It alsodemonstrates how a function may be called more than once in a given program andprocess differentdata in each call.

    Program to Sort Three Numbers1./*2. * Tests function order by ordering three numbers3. */4. #include 5.6. void order(double *smp, double *lgp);

  • 8/13/2019 Extention of Unit 4

    4/18

    7.8. int9. 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 variables32. * Post: variable pointed to by smp contains the smaller of the type33. * double values; variable pointed to by lgp contains the larger34. */

    35. void36. 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.5The numbers in ascending order are: 5.50 7.50 9.60

  • 8/13/2019 Extention of Unit 4

    5/18

    identifies smp and lgp as input/output parameters because the function uses thecurrent 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 , andthe 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 asnapshot of the values in memory immediately after execution of this assignmentstatement.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 , thevalue 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 bylgp . This completes the swap of values.

  • 8/13/2019 Extention of Unit 4

    6/18

    A scope in any programming is a region of the program where a defined variablecan 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 localvariables,2. Outside of all functions which is called globalvariables.3. In the definition of function parameters which is called formalparameters.

    Let us explain what are localand globalvariables and formalparameters.

    Local Variables

    Variables that are declared inside a function or block are called local variables. Theycan be used only by statements that are inside that function or block of code. Localvariables 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

    intmain (){/* local variable declaration */inta,b;intc;

    /* actual initialization */a =10;b =20;c =a +b;

    printf ("value of a = %d, b = %d and c = %d\n",a,b,c);

    return0;}

    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 programand 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 isavailable for use throughout your entire program after its declaration. Following isthe example using global and local variables:

  • 8/13/2019 Extention of Unit 4

    7/18

    #include

    /* global variable declaration */intg;

    intmain (){/* local variable declaration */inta,b;

    /* actual initialization */a =10;b =20;g =a +b;

    printf ("value of a = %d, b = %d and g = %d\n",a,b,g);

    return0;}

    A program can have same name for local and global variables but value of localvariable inside a function will take preference. Following is an example:

    #include

    /* global variable declaration */intg =20;

    intmain (){/* local variable declaration */intg =10;

    printf ("value of g = %d\n", g);

    return0;}

    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 thatfunction and they will take preference over the global variables. Following is anexample:

  • 8/13/2019 Extention of Unit 4

    8/18

    #include

    /* global variable declaration */inta =20;

    intmain (){/* local variable declaration in main function */inta =10;intb =20;intc =0;

    printf ("value of a in main() = %d\n", a);c =sum(a,b);printf ("value of c in main() = %d\n", c);

    return0;}

    /* function to add two integers */intsum(inta,intb){

    printf ("value of a in sum() = %d\n", a);printf ("value of b in sum() = %d\n", b);

    returna +b;}

    When the above code is compiled and executed, it produces the following result:

    value of a in main() = 10value of a in sum() = 10value of b in sum() = 20value of c in main() = 30

    Initializing Local and Global Variables

    When a local variable is defined, it is not initialized by the system, you mustinitialize it yourself. Global variables are initialized automatically by the systemwhen you define them as follows:

    Data Type Initial Default Value

    int 0

    char '\0'

    float 0

  • 8/13/2019 Extention of Unit 4

    9/18

    double 0

    pointer NULL

    Array Subscripts:

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

    Using for Loops for Sequential AccessAssume that the name SIZE has been defined to be 11 .int square[SIZE], i;The for loopfor (i = 0; i < SIZE; ++i)square[i] = i * i;

    1./*2. * Computes the mean and standard deviation of an array of data and displays3. * the difference between each value and the mean.4. */5.

    6. #include 7. #include 8.9. #define MAX_ITEM 8/* maximum number of items in list of data */10.11. int12. main(void)13. {14. double x[MAX_ITEM], /* data list */

  • 8/13/2019 Extention of Unit 4

    10/18

    15. mean, /* mean (average) of the data */16. st_dev, /* standard deviation of the data */17. sum, /* sum of the data */18. sum_sqr; /* sum of the squares of the data */19. int i;20.21./* Gets the data */22. printf("Enter %d numbers separated by blanks or s\n> ",23. MAX_ITEM);24. for (i = 0; i < MAX_ITEM; ++i)25. scanf("%lf", &x[i]);26.27./* Computes the sum and the sum of the squares of all data */28. sum = 0;29. sum_sqr = 0;30. for (i = 0; i < MAX_ITEM; ++i) {31. sum += x[i];

    32. sum_sqr += x[i] * x[i];33. }34./* Computes and prints the mean and standard deviation */35. mean = sum / MAX_ITEM;36. st_dev = sqrt(sum_sqr / MAX_ITEM - mean * mean);37. printf("The mean is %.2f.\n", mean);38. printf("The standard deviation is %.2f.\n", st_dev);39.40./* Displays the difference between each item and the mean */41. printf("\nTable of differences between data values and mean\n");42. printf("Index Item Difference\n");

    43. for (i = 0; i < MAX_ITEM; ++i)44. printf("%3d%4c%9.2f%5c%9.2f\n", i, ' ', x[i], ' ', x[i] - mean);45.46. return (0);47. }

    Enter 8 numbers separated by blanks or 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 Difference0 16.00 14.001 12.00 10.002 6.00 4.003 8.00 6.004 2.50 0.505 12.00 10.006 14.00 12.00

  • 8/13/2019 Extention of Unit 4

    11/18

    7 -54.50 -56.50

    The program uses three for loops to process the array x . The constant MAX_ITEMdetermines the size of the array. The variable i is used as the loop control variableand 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 0to 7 ; each repetition gets a new data value and stores it in x[i] . The subscript Idetermines 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 , thevalue 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 addressof 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]);

  • 8/13/2019 Extention of Unit 4

    12/18

    You can also pass array elements as arguments to functions that you write. Eacharray element must correspond to a formal parameter that is the same simple typeas the array element.The function prototype below shows one type double input parameter ( arg_1 ) andtwo 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, thestatement

    do_it (p, &q, &r);

    passes the value of p to function do_it and returns the function results to variablesq 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] isan input argument and x[1] and x[2] are output arguments (see Fig. 7.3 ). Infunction do_it , you can use statements like*arg2_p = ...*arg3_p = ...

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

  • 8/13/2019 Extention of Unit 4

    13/18

    Formal Array ParametersWhen an array name with no subscript appears in the argument list of

    a function call, what is actually stored in the functions corresponding formalparameter is the address of the initial array element. In the function body,we can use subscripts with the formal parameter to access the arrayselements. However, the function manipulates the original array, not its ownpersonal copy, so an assignment to one of the array elements by a statementin the function changes the contents of the original array.

    In function fill_array , the array parameter is declared asint 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, sincewe do not provide the size, we have the flexibility to pass to the function an arrayof any number of integers.

    Argument Correspondence for Array ParametersTo call function fill_array , you must specify the actual array argument, the numberof array elements, and the value to be stored in the array. If y is an array with tentype int elements, the function callfill_array(y, 10, num); stores the value of num in the ten elements of array y . If xis a five-element array oftype int values, the statement fill_array(x, 5, 1); causes function fill_array to store1 in all elements of array x .Figure 7.5 shows the data areas just before the return from the function callfill_array(x, 5, 1);

  • 8/13/2019 Extention of Unit 4

    14/18

    Use of *list Instead of list[] in a Formal Parameter ListIn the declaration for function fill_array , we can use either parameter declaration:int list[]int *list`Arrays as Input Arguments:

  • 8/13/2019 Extention of Unit 4

    15/18

    Returning an Array Result

    The formal parameter list declarationconst double ar1[],const double ar2[],double arsum[],int nindicates that formal parameters ar1 , ar2 , and arsum stand for actual argumentarrays whose elements are of type double and that ar1 and ar2 are strictly inputparameters, as is n . The function can process type double arrays of any size aslong as the preconditions stated in the initial block comment are met. If we assumethat a calling function has declared three five-element arrays x , y , and x_plus_yand has filled x and y with data, the call add_arrays(x, y, x_plus_y, 5); would leadto 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_ywill have these new contents:

  • 8/13/2019 Extention of Unit 4

    16/18

    Searching and Sorting an Array:

    Lab Manual programs are the examplesof 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:

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

    'J' 'o' 'h' 'n'

    'M' 'a' 'r' ' '

    'I' 'v' 'a' 'n'

    is a 3 4 array:3 rows, 4 columns

    'J' 'o' 'h' 'n'

    'M' 'a' 'r' ' '

    'I' 'v' 'a' 'n'

  • 8/13/2019 Extention of Unit 4

    17/18

    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) specifies number of rows

    [4](cols) 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

  • 8/13/2019 Extention of Unit 4

    18/18

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

    In the declaration of two dimensional array the column size should bespecifed, to that it can arrange the elements in the form of rows andcolumns.

    Two-dimensional arrays in C are stored in "row-major format": the array islaid out contiguously, one row at a time:

    To access an element of a 2D array, you need to specify both the row andthe 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 thecompile.

    The general form of multidimensional array istype 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