当前位置:首页 >> 其它课程 >>

Chapter9 User-Defined Functions


Chapter 9 User-Defined Functions

1 November 2013

1

9.1 Introductions
? We have mentioned that one of the strengths of C language is that C functions are

easy to define and use. We have used functions in every program that we have discussed so far, such as main, printf and scanf. In this chapter, we shall consider in detail how a function is designed, how two or more functions are put together and how the communicate with one another.
1 November 2013 2

9.2 Need for User-Defined Functions
? Every C program must have a main function. But if we code any program utilizing only main function, the program may become too large and complex as a result the task of debugging, testing, and maintaining becomes difficult. ? If a program is divided into functional parts, then each part may be independ-ently coded and later combined into a single unit, problems will be solved.
1 November 2013 3

9.2 Need for User-Defined Functions
? Advantages of this “division” approach:
?It facilitates top-down modular programming. ?The length of a source program can be reduced by using functions at appropriate places. ? It is easy to locate and isolate a faulty function for further investigations. ?A function may be used by many other programs.
1 November 2013 4

9.3 A Multi-function Program
? A function is a self-contained block of code that performs a particular task. Once a function has been designed and packed, it can be treated as a ?black box? that takes some data from the main program and return value. ? The inner details of operation are invisible to the rest of the program. All that the program knows about a function is: What goes in and what comes out.
1 November 2013 5

9.3 A Multi-function Program
? Every C program can be designed using a collection of these black boxes known as functions. ? Consider a set of statements as shown below:
void printline (void) { int i; for (i = 1; i < 40; i++) printf(“-”); printf(“\n”); }

1 November 2013

6

9.3 A Multi-function Program
? The above set of statements defines a function called printline, which could print a line of 39-char-acter length. This function void printline (void);/*declaration*/ can be used in a program as follows: main() This program will print the following { output: printline(); -------------------------------------- use printf(“This illustrates the This illustrates the use of C functions of C functions”); -------------------------------------printline();
}
1 November 2013 7

9.3 A Multi-function Program
? The above program contains two userdefined functions: ?main() function ?printline() function

1 November 2013

8

9.3 A Multi-function Program
? The program execution always begins with the main function. ? During execution of the main, the first statement encountered is printline(), so function printline is to be executed. ? After executing the printline function, the control is transferred back to the main. ? After that printf is executed. Then printline is executed for the second time.
1 November 2013 9

9.3 A Multi-function Program
? The main function calls the user-defined function printline two times and the library function printf once. ? The printline function itself calls the library function printf 39 times repeatedly.

1 November 2013

10

9.3 A Multi-function Program
? Any function can call any other function. In fact, it can call itself. ? A ?called function? can also call other functions. ? A function can be called more than once. In fact, this is one of the main features of using functions.

1 November 2013

11

9.3 A Multi-function Program

Modular Programming

1 November 2013

Modular programming is a strategy applied to the design and development of software system. It is defined as organizing a large program into small, independent program segments called modules that are separately named and individually callable program units. These modules are carefully integrated to become a entire software system.

12

9.3 A Multi-function Program

Modular Programming

Modules are identified and designed such that they can be organized into a top-down hierarchical structure. In C, each module refers to a function that is responsible for a single task.

1 November 2013

13

9.3 A Multi-function Program

Modular Programming

Characteristics of modular programming: 1. Each module should do only one thing. 2.Communications between modules is allowed only by calling module. 3.A module can be called by one and only one higher module.
1 November 2013

To be continued…

14

9.3 A Multi-function Program

Modular Programming

Characteristics of modular programming: 4.No communication can take place directly between modules that do not have calling-called relationship. 5.All modules are designed as single-entry, single-exit systems using control structures.
1 November 2013 15

9.4 Elements of User-defined Functions
? Functions are classified as one of the derived data types in C. ? We can define functions and use them like any other variables in C programs. ? There are some similarities between functions and variables in C.

1 November 2013

16

9.4 Elements of User-defined Functions
? Similarities between functions and variables:
?Both function names and variable names are considered identifiers. ?Like variables, functions have types (such as int) associated with them. ?Like variables, function names and their types must be declared and defined before they are used in a program.
1 November 2013 17

9.4 Elements of User-defined Functions

?Three elements of functions:
?Function definition ?Function call ?Function declaration

1 November 2013

18

9.5 Definition of Functions
? A function definition, also known as function implementation shall include the following elements:
?Function name Function ?Function type Header ?List of parameters ?Local variable declarations Function ?Function statements Body ?A return statement
1 November 2013 19

9.5 Definition of Functions

function_type function_name(param list) { local variable declaration; executable statement1; executable statement2; ... ... return statement; }
1 November 2013 20

?General format of a function definition:

9.5 Definition of Functions

?Function Header:
function_type function_name(param list)

?Three parts:
?function type (return type) ?function name ?formal parameter list

1 November 2013

21

9.5 Definition of Functions

?Function Type:
?Type of return value ?Assume to be int if not specified ?void – return nothing ?It is a good programming practice to code explicitly the return type, even when it is an integer.
1 November 2013 22

9.5 Definition of Functions

/*Examples:*/ ?It is the variables a,int b,int c){ float quadratic (intthat will receive the } data sent by the calling program. double power(double x, int n){…} float mul(float used to send values to the ?Can also be x,float y){…} int sum(int programs. calling a,int b){…} int sum(int a,b){…} void?void – no value need to be sent printline(void){…} void printline(){…}
… 1 November 2013 23

?Formal Parameter List:

9.5 Definition of Functions

?Three parts of Function Body:
?Local variables declarations ?Function statements ?Return statement (Can be omitted if
the function returns nothing.)

1 November 2013

24

9.5 Definition of Functions

?Examples of function definitions:
/*Example 1:*/ float mul (float x, float y) { float result;/*local variable*/ /*compute the product*/ result = x * y; /*return the result*/ return result; }
1 November 2013 25

9.5 Definition of Functions

?Examples of function definitions:
/*Example 2:*/ void sum (int a, int b) { /*no local variables*/ printf (“sum = %s”, a + b); return; /*optional*/ }
1 November 2013 26

9.5 Definition of Functions

?Examples of function definitions:
/*Example 3:*/ void display (void) { /*no local variables;*/ printf (“No type, no parameter”); /*no return statement*/ }
1 November 2013 27

9.5 Definition of Functions

?Note:
?When a function reaches its return statement, the control is transferred back to the calling program. ?In the absence of a return statement, the closing brace acts as a void return. ?A local variable is a variable that is defined and used inside a function.
1 November 2013 28

9.6 Return Values And Their Types

?A function may or may not send back any value to the calling function. If it does, it is done through the return statement. ?The called function can only return one value per call, at the most.

1 November 2013

29

9.6 Return Values And Their Types

?The return statement can take one of the following forms:
?return; ?return (expression);

1 November 2013

30

9.6 Return Values And Their Types

?Examples of return statement:
/*Example 1:*/ if (error) return;

1 November 2013

31

9.6 Return Values And Their Types

?Examples of return statement:
/*Example 2:*/ int mul (int x, int y) { int p; p = x * y; return (p); }
1 November 2013 32

9.6 Return Values And Their Types

?Examples of return statement:
/*Example 3:*/ int mul (int x, int y) { return (x * y); }
1 November 2013 33

9.6 Return Values And Their Types

?Examples of return statement:
/*Example 4:*/ if(x <= 0) return (0); else return (1);
1 November 2013 34

9.6 Return Values And Their Types

?Examples of return statement:
/*Example 5:*/ int product(void) { return (2.5 * 3.0); }
1 November 2013 35

9.7 Function Calls

?A function /*Example:*/can be called by simply using int mul (int x, int y) main () the function name followed by a { list of actual parameters (or { arguments). int p; int y; /*Function call*/ y; p = x * y = mul(10,5); return (p); printf }(“%d\n”,y); }
1 November 2013 36

9.7 Function Calls
main() { int y; y = mul (10,5);/*call*/ ...... } int mul (int x, int y) { int p; p = x * y; return (p); }
1 November 2013 37

9.7 Function Calls

?There are many different ways to call mul(10,5) a function. mul(m,5) Listed below are some of the ways the mul(10,n) function mul can be invoked: mul(m,n)
mul(m+5,10) mul(10,mul(m,n)) mul(expression1,expression2)
1 November 2013 38

9.7 Function Calls

?A function which returns a value can be used in expressions like any other printf(“%d\n”, the following variable. Each of mul(p,q)); statements is valid:
y = mul(p,q)/(p+q); if (mul(m,n)>total) printf(“large”);
1 November 2013 39

9.7 Function Calls

?A function can not be used on the right side of an assignment statement.

mul(a,b) = 15;/*Invalid*/

1 November 2013

40

9.7 Function Calls

?A function that does not return any value may not be used in expressions; but can be called in to perform /*Example*/ certain tasks specified in the function. main()
{ printline();

}
1 November 2013 41

Function 9.7 Function Calls Call

A function call is a postfix expression. the operator(..) is at a very high level of precedence. Therefore, when a function call is used as a part of an expression, it will be evaluated first, unless parentheses are used to change the order of precedence
1 November 2013 42

Function 9.7 Function Calls Call

1 November 2013

In a function call, the function name is the operand and the parentheses set (..) which contains the actual parameters is the operator. The actual parameters must match the function’s formal parameters in type, order and number. Multiple actual parameters must be separated by commas.

43

Function 9.7 Function Calls Call

Note:
1. If the actual parameters are more than the formal parameters, the extra actual arguments will be discarded.

1 November 2013

44

Function 9.7 Function Calls Call

Note:
2. On the other hand, if the actual parameters are less than the formals, the unmatched formal arguments will be initialized to some garbage.

1 November 2013

45

Function 9.7 Function Calls Call

Note:
3. Any mismatch in data types may also result in some garbage values.

1 November 2013

46

9.8 Function Declaration

?Like variables, all functions in a C program must be declared , before they are invoked.

1 November 2013

47

Fun_type fun_name(param list);

9.8 Function Declaration

?A function declaration (also known as /*fun is short for function*/ function prototype) consists of four /*param is short for parameter*/ parts:
?Function type (return type) /*Example*/ ?Function name int mul(int m, int n); ?Parameter list /*function prototype*/ ?Terminating semicolon
1 November 2013 48

9.8 Function Declaration

? Points to note:
1. The parameter list must be separated by commas. 2. The parameter names do not need to be the same in the prototype declaration and the function definition. 3. The types must match the types of parameters in the function definition, in number and order.
1 November 2013 49

9.8 Function Declaration

? Points to note:
4. Use of parameter names in the declaration is optional. 5. If the function has no formal parameters, the list is written as (void). 6. The return type is optional, when the function returns int type data.
1 November 2013 50

9.8 Function Declaration

? Points to note:
7. The retype must be void if no value is returned. 8. When the declared types do not match with the types in the function definition, compiler will produce an error.

1 November 2013

51

9.8 Function Declaration

?Equally acceptable forms of declaration of mul function are:
int mul (int, int); mul (int a, int b); mul (int, int);

1 November 2013

52

9.8 Function Declaration

?When a function does not take any parameters and does not return any value, its prototype is written as:
void display(void);

1 November 2013

53

9.8 Function Declaration

? A prototype declaration may be placed in two places in a program:
1. Above all the functions (including main) -- as a global prototype. 2. Inside a function definition. -- as a local prototype.

1 November 2013

54

9.8 Function Declaration

?The place of declaration of a function defines a region in a program in which the function may be used by other functions. ?This region is known as the scope of the function.

1 November 2013

55

Prototype: Yes 9.8 Function Declaration or No

Prototype declaration are not essential. If a function has not been declared before it is used, C will assume that its details available at the time of linking.

1 November 2013

56

Prototype: Yes or 9.8 Function DeclarationNo (contd)

Since the prototype is not available, C will assume that the return type is an integer and that the types of parameters match the formal definitions.

1 November 2013

57

Prototype: Yes or No 9.8 Function Declaration (contd)

If these assumptions are wrong, the linker will fail and we will have to change the program. The moral is that we must always include prototype declarations, preferably in global declaration section.

1 November 2013

58

Parameters Everywhere! 9.8 Function Declaration

Parameters (also known as arguments) are used in these places: 1. In declaration (prototypes) 2. In function call 3. In function definition

1 November 2013

59

Parameters Everywhere! 9.8 Function Declaration

The parameter used in prototypes and function definitions are called formal parameters and those used in function calls are called actual parameters. Actual parameters used in a calling statement may be simple constants, variables or expressions.
1 November 2013 60

Parameters Everywhere! 9.8 Function Declaration

The formal and actual parameters must match exactly in type, order and number. Their names, however, do not need to match.

1 November 2013

61

9.9 Category of Functions

? A function, depending on whether arguments are present or not and whether a value is returned or not, may belong to one of the following categories:
1. Function with no arguments and no return type. 2. Function with arguments and no return type.
1 November 2013 62

9.9 Category of Functions
3. Function with arguments and one return type. 4. Function with no arguments but return a value. 5. Functions that return multiple values.
In the sections to follow, we shall discuss these categories with examples.
1 November 2013 63

9.10 No Arguments and No Return Values

? When a function has no arguments, it does not receive any data from the calling function or return a value.
function1() { ...... ...... function2(); ...... ...... }
1 November 2013

function2() { ...... No input . . . . . . ...... No output . . . . . . ...... }

control

control

64

9.10 No Arguments and No Return Values

? A function that does not return any value cannot be used in an expression. ? It can only be used as an independent statement.

1 November 2013

65

9.10 No Arguments and No Return Values

? Example 9.1 : Write a program with multiple functions that do not communication any data between them.

1 November 2013

66

9.10 No Arguments and No Return Values Program:
/*Function declaration*/ void printline(void); void value(void); main() { printline(); value(); printline(); }
1 November 2013

67

9.10 No Arguments and No Return Values
/*Function1: printline() */ void printline(void)/*no arguments*/ { int i; for(i=1;i <= 35; i++) printf(“%c”,?-?); printf(“\n”); }
1 November 2013 68

9.10 No Arguments and No Return Values /* Function2: value() */ void value(void) /*no arguments*/ { int year, period; float inrate, sum, principal;
printf (“Principal amount? scanf (“%f”, &principa); printf (“Interest rate? scanf (“%f”, &inrate); printf (“Period? scanf (“%d”, &period); ”);

”);
”);
69

1 November 2013

9.10 No Arguments and No Return Values

sum = principal; year = 1; while (year <= period) { sum = sum * (1+inrate); year = year + 1; } printf (“\n%8.2f %5.2f %5d %12.2f\n”,principal,inrate, period,sum);
70

}
1 November 2013

9.10 No Arguments and No Return Values
Output:
----------------------------------Principal amount? 5000 Interest rate? 0.12 Period? 5 5000.00 0.12 5 8811.71 -----------------------------------

1 November 2013

71

9.11 Arguments But No Return Values
? The nature of data communication between the calling function and the called function with arguments but return values is show below:
function1() { ...... ...... function2(a); ...... ...... }
1 November 2013

Values of function2(f) { arguments ...... ...... ...... No return ...... value ...... }

72

9.11 Arguments But No Return Values
? We shall modify the definitions of both the called functions to include arguments as follows:
void printline (char ch) void value (float p, float r, int n)

1 November 2013

73

9.11 Arguments But No Return Values
? They are called like this:
printline(?-?); value (500, 0.12, 5);

1 November 2013

74

9.11 Arguments But No Return Values
Function call

Called function

main(){ actual arguments ...... function1(a1,a2,a3,...,am); ...... } function1(f1,f2,f3,...,fm){ ...... formal arguments }

1 November 2013

75

9.11 Arguments But No Return Values
? Make sure that the function call has matching arguments. ? The formal arguments must be valid variable names. The actual arguments my be variable names, expressions, or constants. ? The variable used in actual arguments must be assigned values before call the function call is made.
1 November 2013 76

9.11 Arguments But No Return Values
? When a function call is made, only a copy of the values of actual arguments is passed into the called function. ? What occurs inside the function will have no effect on the variables used in the actual argument list.

1 November 2013

77

9.11 Arguments But No Return Values

? Example 9.2 : Modify the program of Example 9.1 to include the arguments in the function calls.

1 November 2013

78

9.11 Arguments But No Return Values Program:
/*prototypes*/ void printline(char c); void value(float, float, int); main() { float pricipal, inrate; int period; printf(“Enter principal amount, interest rate,and period\n”);
1 November 2013 79

scanf(“%f %f %d,&principal, 9.11 Arguments But No Return Values &inrate,&period”); printline(?Z?); value(pricipal,inrate,period); printline(?C?);

} void printline(char ch){ int i; for (i = 1; i <= 52; i++) printf(“%c”,ch); printf(“\n”); }
1 November 2013 80

void value (float p,float r,int n) 9.11 Arguments But No Return Values { int year; float sum; sum = p year = 1; while(year <= n) { sum = sum * (1+r); year = year + 1; } printf(“%f\t%f\t%d\t%f\n”, p,r,n,sum); }
1 November 2013 81

9.11 Arguments But No Return Values

Output: Enter principal amount, interest rate, and period 5000 0.12 5 ZZZZZZZZZZZZZZZ...(52 Zs)...ZZZZZZZZZZZZZZ 5000.000000 0.120000 5 8811.708984 CCCCCCCCCCCCCCC...(52 Cs)...CCCCCCCCCCCCCC

1 November 2013

82

Variable Number of Arguments 9.11 Arguments But No Return Values Some functions have a variable number of arguments and data types which can not be known at compile time. The printf and scanf function are typical examples.

1 November 2013

83

Variable Number of Arguments 9.11 Arguments But No Return Values
The ANSI standard proposes new symbol called the ellipsis to handle such function. The ellipsis of three periods(…) and used as shown below: double area(float d, …) Both the function declaration and definition should use ellipsis to indicate that the arguments are arbitrary both in number and type.
1 November 2013 84

9.12 Arguments with Return Values
? Functions receive data from the calling function through arguments and return some value:
function1() { ...... ...... function2(a); ...... ...... }
1 November 2013

Values of function2(f) { arguments ...... ...... ...... Function ...... result return (e); }
85

9.12 Arguments with Return Values
? Example 9.3 : In the program presented example 9.2, modify the function value, to return the final amount calculated to the main, which will display the required output at the terminal. Also extend the versatility of the line as an argument.
1 November 2013 86

Program: 9.12 Arguments with Return Values void printline(char c, int len); value(float, float, int); main() { float pricipal, inrate, amount; int period; printf(“Enter principal amount, interest rate,and period\n”); scanf(“%f %f %d,&principal, &inrate,&period”);
1 November 2013 87

printline(?*?,52); 9.11 Arguments But No Return Values

amount = value(pricipal, inrate,period); printf(“\n%f\t%f\t%d\t%f\n\n”, principal,inrate,period,amount); printline(?=?,52);

} void printline(char ch, int len){ int i; for (i = 1; i <= len; i++) printf(“%c”,ch); printf(“\n”); }
1 November 2013

88

/*default return type*/ 9.11 Arguments But No Return Values value (float p,float r,int n) { int year; float sum; sum = p year = 1; while(year <= n) { sum = sum * (1+r); year = year + 1; } /*return int part of sum*/ return (sum); }
1 November 2013 89

9.12 Arguments with Return Values

Output: Enter principal amount, interest rate, and period 5000 0.12 5 ****************...(52 *s)...**************** 5000.000000 0.120000 5 8811.000000 ============...(52 =s)...=============

1 November 2013

90

9.12 Arguments with Return Values
? Returning Float Values: ? Example 9.4 : Write a function power that computes x raised to the power y for integers x and y and returns double-type value.

1 November 2013

91

9.12 Arguments with Return Values Program:
main() { int x,y; /*input data*/ /*prototype decalration*/ double power(int,int); printf(“Enter x,y”); scanf(“%d %d”,&x,&y); printf(“%d to power %d is %f\n”, x,y,power(x,y)); }
1 November 2013 92

9.12 power(int x, Return double Arguments withint y) Values { double p; p = 1.0;/*x to power zero*/ if (y >= 0) while(y--)/*positive powers*/ p *= x; else while(y++)/*negative powers*/ p /= x; return(p);/*returns double type*/ }
1 November 2013 93

9.12 Arguments with Return Values
Enter x,y:16 2 16 to power 2 is 256.000000 Enter x,y:16 -2 16 to power -2 is 0.003906

1 November 2013

94

9.13 No Arguments But Returns A Value

? There are some functions that take no arguments but returns a value, for example getchar declared in the header file <stdio.h>. ? The getchar function has no parameters but it returns an integer type data that represents a character.
1 November 2013 95

9.13 No Arguments But Returns A Value
? Example: int get_number(void); main() { int m = get_number(); printf(“%d”,m); } int get_number(void) { int number; scanf(“%d”,&number); return(number); }
1 November 2013

96

9.14 Functions That Return Multiple Values

? One C function can contain only one return statement which returns only one value. What if we want to get more information from a function? ? We can achieve this in C using the arguments not only to receive information but also send back information (output parameters) to the calling function.
1 November 2013 97

9.14 Functions That Return Multiple Values

? The mechanism of sending back information though arguments is achieved using what are known as the address operator (&) and indirection operation (*).

1 November 2013

98

9.14 Functions That Return Multiple Values

? Example:
void mathoperation(int x,int y, int *s,int *d) { *sum = a+b; *diff = a-b; } main() { int x=20,y=10,s,d; mathoperation(x,y,&s,&d); printf(“s=%d\n d=%d\n”,s,d); }
1 November 2013

99

Rules for Passing by Pointers 9.14 Functions That Return Multiple Values

1 November 2013

1. The types of the actual formal arguments must be same. 2. The actual arguments (in the function call) must be the address of variables that are local to the calling function 3. The formal arguments in the function header must be prefixed by the indirection operator *.

100

9.14 Functions That Return Multiple Values Rules for Passing by Pointers 4. In the prototype, the arguments must be prefixed by the symbol *. 5. To access the value of an actual argument in the called function, we must use the corresponding formal argument prefixed with the indirection operator *.
1 November 2013 101

9.15 Nesting of Functions
? C permits nesting of functions freely. main can call function1, which calls function2, which call fucntion3, …… and so on. There is in principle no limit as to how deeply functions can be nested.

1 November 2013

102

float Nesting of Functions ratio(int x,int y,int z) 9.15 { if (difference(y,z)) return (x/(y-z)); ? Example: else return(0.0); } int difference(int p,int q) { if(p != q) return(1); else return (0); } main() { int a,b,c; scanf(“%d %d %d”,&a,&b,&c); printf(“%f \n”, ratio(a,b,c)); }
1 November 2013

103

9.16 Recursion
? When a called function in turn calls another function, a process of ?chaining? occurs. Recursion is a special case of this process, where a function calls itself.

1 November 2013

104

9.16 Recursion
? A very simple example of recursion is presented below:
main() { printf(“This is an example of” + “ recursion\n”); main(); The execution } will continue output: This is an example of indefinitely. recursion This is an example of recursion ......
1 November 2013 105

9.16 Recursion
? Another example: the factorial number n is expressed as a series of repetitive multiplications as shown below: factorial of n = n(n-1)(n-2)……1.
factorail(int n) { int fact; if(n==1) return(1); else fact = n*factorial(n-1); return(fact); }
1 November 2013

106

9.16 Recursion
? Let us see how the recursion works. Assume n=3. Since the value of n is no 1, the statement fact=n*factorial(n-1); will be executed with n=3. That is fact=3*factorial(2); will be evaluated. (To be continued…)
1 November 2013 107

9.16 Recursion
The expression on the right-hand side include a call to factorial with n=2. This call will return the following value: 2*factorial(1); Once again, factorial is called with n=1. This time, the function returns 1. (To be continued…)
1 November 2013 108

9.16 Recursion
The sequence of operations can be summarized as follows: fact = 3 * factorial(2) = 3 * 2 * factorial(1) =3*2*1 =6

1 November 2013

109

9.16 Recursion
? Recursive functions can be effectively used to solve problems where solution is expressed in terms of successively applying the same solution to subsets of the problem.

1 November 2013

110

9.16 Recursion
? When we writer recursive functions, we must have an if statement somewhere to force the function to return without the recursive calling being executed. Otherwise, the function will never return.

1 November 2013

111

9.17 Passing Arrays to Functions
? Like the values of simple variables, it is also possible to pass the values of an array to a function. ? To pass an one-dimensional array to a called function, it is sufficient to list the name of the array without any subscripts, and the size of the array as arguments.
1 November 2013 112

main()Passing Arrays to Functions 9.17 { float largest(float a[], int n); float value[4]={2.5,-4,1.2,3.1}; ? Example: find the largest member printf(“%f\n”, largest(value,4)); of an array } float largest(float a[],int n) { int i; float max; max = a[0]; for(i=1;i<n;i++) if(max < a[i]) max = a[i]; return(max); }
1 November 2013 113

9.17 Passing Arrays to Functions
? Example 9.5: Write a program to calculate the standard deviation of an array of values. The array elements are read from the terminal. Use functions to calculate standard deviation and mean.

1 November 2013

114

Program 9.17 Passing Arrays to Functions #include <math.h> #define SIZE 5 float std_dev(float a[], int n); float mean(float a[], int n); main() { float values[SIZE]; int i; printf(“Enter %d float values\n” , SIZE); for (i=0;i<SIZE;i++) scanf(“%f,”&value[i]); printf(“Std.deviation is %f\n”, std_dev(value,SIZE)); }
1 November 2013 115

9.17 Passing Arrays to Functions
float std_dev(float a[], int n) { int i; float x, sum=0.0; x = mean(a,n); for(i=0;i<n;i++) sum+=(x-a[i])*(x-a[i]); return (sqtr(sum/(float)n)); }
1 November 2013 116

float mean (float a[], int n) 9.17 Passing Arrays to Functions { int i; float sum = 0.0; for (i=0;i<n;i++) sum = sum + a[i]; return (sum/(float)n); } Output Enter 5 float values 35.0 67.0 79.5 14.20 55.75 Std.deviation is 23.231582
1 November 2013 117

Three Rules to Pass an Array 9.17 Passing Arrays to Functions to A Function

1 November 2013

1. The function must be called by passing only the name of the array. 2. In the function definition, the formal parameter must be an array type; the size of the array does not need to be specified. 3. The function prototype must show that the argument is an array.

118

9.17 Passing Arrays to Functions
? Example 9.6: Write a program that uses a function to sort an array of integers.

1 November 2013

119

Program

9.17 Passing Arrays to Functions

void sort(int m, int x[]); main() { int i; int marks[5] = {40,90,73,81,35}; printf(“Marks before sorting\n”); for(i=0;i<5;i++) printf(“%d”,marks[i]); printf(“\n\n”); sort(5,marks); printf(“Marks after sorting\n”);
1 November 2013 120

for (i=0;i<5;i++) 9.17 Passing Arrays to Functions printf(“%4d”,marks[i]); printf(“\n”); } void sort(int m,int x[]) { int i,j,t; for(i=1;i<=m-1;i++) for(j=1;j<=m-1;j++) if(x[j-i]>=x[j]) { t = x[j-i]; x[j-i] = x[j]; x[j] = t; } }
1 November 2013

121

9.17 Passing Arrays to Functions
Output Marks before sorting 40 90 73 81 35 Marks after sorting 35 40 73 81 90

1 November 2013

122

9.17 Passing Arrays to Functions
? Like simple arrays, we can also pass multidimensional arrays to functions. ? Rules:
1. The function must be called by passing only the array name. 2. In the function definition, we must indicate that the array has two dimensions by including two sets of brackets.
1 November 2013 123

9.17 Passing Arrays to Functions
3. The size of the second dimension must be specified. 4. The prototype declaration should be similar to the function header.

1 November 2013

124

9.17 Passing Arrays to Functions
? The function given below calculates the average of the values in a twodimensional matrix.
double average(int x[][N],int M,int N) { int i,j; double sum = 0.0; for (i=0; i < M; i++) for (j=1; j < N; j++) sum += x[i][j]; return (sum/(M*N)); }
1 November 2013 125

9.17 Passing Arrays to Functions
? The function can be used in a main function as illustrated below:
main() { int M=3,N=2; double average(int[][N],int,int); double mean; int matrix [M][N] = {{1,2},{3,4},{5,6}}; mean = average(matrix,M,N); ...... }
1 November 2013 126

9.18 Passing Strings to Functions
? Because the strings are treated as character arrays in C, the rules for passing strings to functions are very similar to those for passing arrays to functions.

1 November 2013

127

9.18 Passing Strings to Functions
? Basic rules:
1. The string to be passed must be declared as a formal argument of the function when it is defined. Example: void display(char item_name[]);

2. The function prototype must show that the argument is a string. For the above function definition, the prototype can be written as void display(char str[]);
1 November 2013 128

9.18 Passing Strings to Functions
3. A call to the function must have a string array name without subscripts as its actual argument. Example: display (names); when names is a properly declared string array in the calling function.

1 November 2013

129

Pass by Value versus Pass by 9.18 Passing Strings to Functions Pointers The technique used to pass data from one function to another is known as parameter passing. Parameter passing can be done in two ways. 1. Pass by value (call by value) 2. Pass by pointers (call by pointers) (To be continued…)
1 November 2013 130

Pass by Value versus Pass by 9.18 Passing Strings to Functions Pointers (continued)
In pass by value, values of actual parameters are copied to the variables in the parameter list of the called function. The called function works on the copy and not on the original values of the actual parameters. This ensures that the original data in the calling function cannot be changed accidentally. (To be continued…)

1 November 2013

131

Pass by Value versus Pass by 9.18 Passing Strings to Functions Pointers (continued)
In pass by pointers (also known as pass by address), the memory addresses of the variables rather than the copies of values are sent to the called function. In this case, the called function directly works on the data in the calling function an the changed values are available in the calling function for its use. ( To be continued…)

1 November 2013

132

Pass by Value versus Pass by 9.18 Passing Strings to Functions Pointers (continued) Pass by pointers method is often used when manipulating arrays and strings. This method is also used when we require multiple values to be returned by the called function.

1 November 2013

133

9.19 The Scope, Visibility and Lifetime of Variables

? In C not only do all variables have a data type, they also have a data type, they also have a storage class. The following variable storage classes are most relevant to functions:
1. 2. 3. 4. Automatic variables External variables Static variables Register variables
134

1 November 2013

9.19 The Scope, Visibility and Lifetime of Variables

? Automatic variables – declared inside a function in which they are to be utilized. They are created when the function is called and destroyed automatically when the function is exited, hence the name automatic. Automatic variables are therefore private (or local) to the function in which they are declared. Because of this property, automatic variables are also referred to as local or internal variables.
1 November 2013 135

9.19 The Scope, Visibility and Lifetime of Variables

? A variable declared inside a function without storage class specification is, by default, an automatic variable. For instance, the storage class of the variable number in the example below in automatic.
main() { int number; ...... }

1 November 2013

136

9.19 The Scope, Visibility and Lifetime of Variables

? We may also use the keyword auto to declare automatic variables explicitly.
main() { auto int number; ...... }

1 November 2013

137

9.19 The Scope, Visibility and Lifetime of Variables

? One important feature of automatic variables is that their value cannot be changed accidentally by what happens in some other function in the program. This assures that we may declare and use the same variable name in different functions in the same program without causing any confusion to the compiler.
1 November 2013 138

9.19 The Scope, Visibility and Lifetime of Variables

? Example 9.7: Write a multifunction program to illustrate how automatic variables work.

1 November 2013

139

Program 9.19 The Scope, Visibility and Lifetime of Variables

void function1(void); void function2(void); main() { int m = 1000; function2(); printf(“%d\n”,m);/*Third output*/ } void function1(void) { int m = 10; printf(“%d\n”,m);/*First output*/ }
1 November 2013 140

9.19 The Scope, Visibility and Lifetime of Variables void function2(void) { int m = 100; function1(); printf(“%d\n”,m);/*Second output*/ }
Output 10 100 1000
1 November 2013 141

9.19 The Scope, Visibility and Lifetime of Variables

? External Variables – Variables that are both alive and active throughout the entire program are known as external variables. They are also known as global variables. Unlike local variables, global variables can be accessed by any function in the program.
1 November 2013 142

9.19 The Scope, Visibility and Lifetime of Variables

? External variables are declared outside a function. For example, the external declaration of integer number and length might appear as:
int number; float length = 7.5; main() {......} function1() {......}

1 November 2013

143

9.19 The Scope, Visibility and Lifetime of Variables

? Consider the following example:
int count; main() { count = 10; Referencing only ...... the local variable, } not function1() the global { int count one. = 0; ...... count = count + 1; }

1 November 2013

144

9.19 The Scope, Visibility and Lifetime of Variables

? Example 9.8: Write a multifunction program to illustrate the properties of global variables.

1 November 2013

145

9.19 The Program Scope, Visibility and Lifetime of Variables
int fun1(void); int fun2(void); int fun3(void); int x; /*global*/ main() { x = 10;/*global x*/ printf(“x = %d\n”,x); printf(“x = %d\n”,fun1()); printf(“x = %d\n”,fun2()); printf(“x = %d\n”,fun3());

}

1 November 2013

146

fun1(void) 9.19 The Scope, Visibility and Lifetime of Variables { x = x + 10; } int fun2(void) { int x; /*local*/ x = 1; return (x); } fun3(void) { x = x + 10; /*global*/ }
1 November 2013 147

9.19 The Output Scope, Visibility and Lifetime of Variables x = 10 x = 20 x=1 x = 30

******************************* Once a variable has been declared as global, any function can use it and change its value. Then, subsequent can reference only that new value. *******************************
1 November 2013

148

Global Variables and Lifetime of Variables 9.19 The Scope, Visibility as Parameters

Since all function in a program source file can access global variables, they can be used for passing values between the functions. However, using global variables as parameters for passing values poses certain problems.
(To be continued...)
1 November 2013 149

Global Variables and Lifetime of Variables 9.19 The Scope, Visibility as Parameters
(continued)

1 November 2013

1. The values of global variables which are sent to the called function my be changed inadvertently by the called function. 2. Functions are supposed to be independent and isolated modules. This character is lot, if they use global variables. (To be continued…)

150

9.19 The Scope, Visibility and Lifetime of Variables (continued)

Global Variables as Parameters

3. It is not immediately apparent to the reader which values are being sent to the called function. 4. A function that uses global variables suffers from reusability.

1 November 2013

151

9.19 The Scope, Visibility and Lifetime of Variables

? One other aspect global variable is that it is y has not been declared yet, of a available only form the point declaration to the end of occurs. so compile error will the program. main() Consider the following program { y =Global variables are 5; segment: initialized to zero by default. ......;
} int y; /*global declaration*/ y=0+1=1 func1() { y = y + 1; }

1 November 2013

152

9.19 The Scope, Visibility and Lifetime of Variables

? External Declaration: In the program segment //Example above, the main cannot access the variablethe variable y has been main() Although y as it has been declared { after the main function. This problem /*external both the functions, defined afterdeclaration*/ extern int declaration of the external y;declaring the y inside can be solved by variable ......} the functions class extern. with the storage informs the compiler fun1()
{

that y is an integer type defined /*external declaration*/ somewhere else in the program. extern int y;
......}

1 November 2013

int y; /*definition*/

153

9.19 The Scope, Visibility and Lifetime of Variables main() ? Note that extern declaration does not { int i; allocate storage space for variables. In void print_out(void); case of arrays, theheight[]; should extern float definition ...... include their size as well. Example: print_out(); } void print_out(void) { extern float height[]; int i; ......} float height[SIZE];
1 November 2013 154

9.19 The Scope, Visibility and Lifetime of Variables extern float height[]; ? An extern within a function provides main() type information to just definition { theThe distinction between that one int i; function.print_out(void); void We can provide type and declaration also applies to ...... functions. information to all functions within a print_out(); fileThe placing external declarations by declaration } void print_out(void) before any of them. Example: voidis equivalent to print_out(void) { int i; extern void pirnt_out(void) ...... } float height[SIZE];
1 November 2013 155

9.19 The Scope, Visibility and Lifetime of Variables

? Static Variables: The value of static variable persists until the end of the program. ? A variable can be declared static using the keyword static like static int x; static float y;
1 November 2013 156

9.19 The Scope, Visibility and Lifetime of Variables

? A static variable may be either an internal type of an external type depending on the place of declaration.

1 November 2013

157

9.19 The Scope, Visibility and Lifetime of Variables

? Example 9.9: Write a program to illustrate the properties of a static variable.

1 November 2013

158

9.19 The Program Scope, Visibility and Lifetime of Variables
void stat(void); main() { in i; for (i=1; i<=3; i++) stat(); } void stat(void) { static int x = 0; x = x + 1; printf(“x = %d\n”,x); }
1 November 2013

Output x=1 x=2 x=3
159

9.19 The Scope, Visibility and Lifetime of Variables

? Register Variables: We can tell the compiler that a variable should be kept in one of the machine?s registers, instead of keeping in the memory (where normal variables are stored). //Example: Since a register access is much faster register int count; than a memory access, keeping the frequently accessed variables (e.g., loop control variables) in the register will lead to faster execution of programs.
1 November 2013 160

Scope and Lifetime of Variables (1/2)
Storage Classes None
Entire file plus other files where variable is declared with extern extern Before all Entire file plus functions in a other files where file (cannot variable is be initialized) declared extern and the file where originally declared as 1 November 2013 global.

Where declared Before all functions in a file (may be initialized)

Visibility (Active)

Lifetime (Alive) Entire program (Global)

Global

161

Scope and Lifetime of Variables (2/2)
Storage Where declared Classes static Before all functions in a file None or Inside a auto function (or block) register Inside a function or block Visibility (Active) Only in that function or block Only in that function or block Only in that function or block Lifetime (Alive) Global

Until end of function or block Until end of function or block

static Inside a 1 November 2013 function

Only in that function

Global 162

9.19 The Scope, Visibility and Lifetime of Variables

? Nested Blocks: A set of statements enclosed in a set of braces is known as a block or a compound statement. Note that all functions including the main use compound statement. A block can have its own declarations and other statements. It is also possible to have a block of such statements inside the body of a function or another block, thus creating what is known as nested blocks.
1 November 2013 163

main() { ? Example of nested blocks: int a = 20; int b = 10; ...... { Outer int a = 0; Inner block int c = a + b; block ...... } b = a; }
1 November 2013 164

9.19 The Scope, Visibility and Lifetime of Variables

9.19 The Scope, Visibility and Lifetime of Variables Scope Rules (1/4)

The region of a program in which a variable is available for use. Visibility The program’s ability to access a variable from the memory. Lifetime The lifetime of a variable is the duration of time in which a variable exists in the memory during execution.
1 November 2013 165

9.19 The Scope, Visibility and Lifetime of Variables Scope Rules (2/4)

Rules of use 1.The scope of a global variable is the entire program file. 2. The scope of a local variable begins at point of declaration and ends at the end of the block or function in which it is declared. 3. The scope of a formal function argument is its own function.
1 November 2013 166

Scope Rules (3/4) 9.19 The Scope, Visibility and Lifetime of Variables 4. The lifetime (or longevity) of an auto variable declared in main is the entire program execution time, although its scope is only the main function. 5. The life of an auto variable declared in a function ends when the function is exited. 6. A static local variable, although its scope is limited to its function, its lifetime extends till the end of program execution.
1 November 2013 167

9.19 The Scope, Visibility and Lifetime of Variables

Scope Rules (4/4)

7. All variables have visibility in their scope, provided they are not declared again. 8. If variable is redeclared within its scope again, it loses its visibility in the scope of the redeclared variable.

1 November 2013

168

9.20 Multifile Programs
? In real-life programming environment, we may use more than one source file which may be compiled separately and linked later to form an executable object code. ? This approach is very useful because any change in one file does not affect other files thus eliminating the need for recompilation of the entire program.
1 November 2013 169

9.20 Multifile Programs
? Multiple source files can share a variable provided it is declared as an external variable appropriately. ? Variables that are shared by two or more files are global variables and therefore we must declare them accordingly in one file and then explicitly define them with extern in other files.
1 November 2013 170

9.20 Multifile Programs
? Example:
//file1.c main() { extern int m; int i; ...... } function1() { int j; ...... 1 November 2013 } //file2.c /*global variable*/ int m; main() { int i; ...... } function3() { int count; ...... 171 }

9.20 Multifile Programs
? A modification of the above program:
//file1.c /*global variable*/ int m; main() { int i; ...... } function1() { int j; ...... 1 November 2013 } //file2.c extern int m; main() { int i; ...... } function3() { int count; ...... }

172

作业
? P299 9.7 9.10

1 November 2013

173


相关文章:
Answer to Chapter9
Answer to Chapter9_英语学习_外语学习_教育专区。Problems 1.Please use examples to illustratethe four modes of supply in transport services Answer: ( ...
chapter9测试
44页 免费 Chapter9第9章 22页 20财富值 Chapter9 第9章 27页 免费 chapter9-3 33页 8财富值 chapter9_1_1 39页 免费 第九章chapter9 29页 1财富值...
Chapter 9 Questions
Chapter 9 Questions_英语考试_外语学习_教育专区。... Keystroke logging captures and records user ...functions used to encrypt or decrypt a message. ...
Chapter 9 反译法 课后练习答案
Chapter 9 反译法 Drills 9.1.1 4. 我认为,安理会不能也不应对这些极其严重的侵犯人权的行为漠 不关心(袖手旁观)。 5.我们认为,他今天上午发言的要旨和口气...
C程序chapter9练习
C程序chapter9练习_理学_高等教育_教育专区 暂无评价|0人阅读|0次下载|举报文档 C程序chapter9练习_理学_高等教育_教育专区。m今日推荐 ...
现代财务管理 Chapter9 答案
CHAPTER 9 CAPITAL BUDGETING AND CASH FLOW ANALYSIS ANSWERS TO QUESTIONS: 1....through the use of the appropriate required return used to evaluate a ...
chapter9 压强与浮力(答案一)
chapter9 压强与浮力(答案一)_理化生_初中教育_教育专区 暂无评价|0人阅读|0次下载|举报文档 chapter9 压强与浮力(答案一)_理化生_初中教育_教育专区。第九章 ...
Chapter 9 统计指数 作业
Chapter9 统计指数 作业 姓名: 王于 专业:工程管理 统计学课程学号:55 一、单项选择 1、商品销售额实际增加 400 元,由于销售量增长使销售额增加 420 元,由于...
Study Questions Chapter9 with key
Study Questions Chapter9 with key_文学_高等教育_教育专区。演讲的艺术考试...Use parallel wording for subpoints and sub-subpoints. 42. All of the ...
ABB DCS 培训课程 T315-12 User defined FB Types - RevA
System 800xA training Chapter 12 User defined ...9 / 21 148153350.doc 3. Accept all this by ...NOTE! It is possible to move functions or ...
更多相关标签: