Presentation is loading. Please wait.

Presentation is loading. Please wait.

A First Book of ANSI C Fourth Edition Chapter 6 Modularity Using Functions: Part I.

Similar presentations


Presentation on theme: "A First Book of ANSI C Fourth Edition Chapter 6 Modularity Using Functions: Part I."— Presentation transcript:

1 A First Book of ANSI C Fourth Edition Chapter 6 Modularity Using Functions: Part I

2 A First Book of ANSI C, Fourth Edition2 Objectives Function and Parameter Declarations Returning a Value Case Study: Calculating Age Norms Standard Library Functions Common Programming and Compiler Errors

3 A First Book of ANSI C, Fourth Edition3 Although printf ( ) and scanf ( ) functions have been enormously helpful to us, it is now time to create our own useful functions, in addition to the main ( ) function that is required in all programs. In this chapter we learn how to write these functions, pass data to them, process the passed data and return a result to the calling function.

4 A First Book of ANSI C, Fourth Edition4 6.1 Function and Parameter Declarations As we have already seen with the printf ( ) and scanf ( ) functions, a function is called, or used, by giving the function’s name and passing any data to it in the parentheses following the function’s name (see Figure 6.1). The called function must be able to accept the data passed to it by the function doing the calling. Only after the called function successfully receives the data can be manipulated to produce a useful result.

5 A First Book of ANSI C, Fourth Edition5 To clarify the process of sending and receiving data, consider Program 6.1, which calls a function named findMax ( ). The program, as shown, is not yet complete. Once the function findMax ( ) is written and included in Program 6.1, the completed program, consisting of the functions main ( ) and findMax ( ), can be run.

6 A First Book of ANSI C, Fourth Edition6 Program 6.1 #include float findMax( float, float); /* the function declaration (prototype) */ int main ( ) { float firstnum, secnum, maxnum; printf (“Enter a number: “); scanf (“%f”, &firstnum); printf (“\nGreat! Please enter a second number:”); scanf (“%f”, &secnum); maxnum = findMax ( firstnum, secnum); /* the function is called here */ printf (“\nThe maximum of the two numbers entered is %f ”,maxnum); return 0; }

7 A First Book of ANSI C, Fourth Edition7 The function findMax ( ) is referred to as the called function, since it is called or summoned into action by its reference in the main ( ) function. The function that does the calling, in this case main ( ), is referred to as the calling function. The terms “called” and “calling” come from standard telephone usage, where one party calls the other on the telephone.

8 A First Book of ANSI C, Fourth Edition8 The called function, in this case findMax ( ), is declared as expecting to receive two floating point values and as returning one floating point value. This declaration is formally referred as a function prototype, and is described in detail later in this section. Let us now see how to write the function findMax ( ).

9 A First Book of ANSI C, Fourth Edition9 Function and Parameter Declarations (continued)

10 A First Book of ANSI C, Fourth Edition10 Function Prototypes Before a function can be called, it must be declared by the function that will do the calling. The declaration statement for a function is formally referred to as a function prototype. The function prototype tells the calling function the type of value that will be returned; if any, and the data of type values that the calling function should transmit to the called function.

11 A First Book of ANSI C, Fourth Edition11 For example, the function prototype previously used in Program 6.1: float findMax ( float, float ); declares that the function findMax( ) expects two floating point values to be sent to it, and that this particular function returns a floating point value.

12 A First Book of ANSI C, Fourth Edition12 Function prototypes may be placed with the variable declaration statements within the calling function, above the calling function name as in Program 6.1, or in a separate header file that is included using a # include preprocessor directive. Placing the prototype before main ( ) makes this declaration available to all functions in the file, thus permitting all functions to call findMax ( ). Placing the prototypes within main ( ) makes the declaration available only to main ( ), which only gives main ( ) the right to call it.

13 A First Book of ANSI C, Fourth Edition13 Similarly, any other function that needs to use findMax ( ) can also include the prototype within itself. In this text, we will always list a prototype at the top of a file so that the single declaration serves for all functions in the file.

14 A First Book of ANSI C, Fourth Edition14 The syntax of function prototype statements is returnDataType functionName ( list of argument data types);

15 A First Book of ANSI C, Fourth Edition15 Calling a function Calling a function is a rather easy operation. The only requirements are that the name of the function be used and that any data passed to the function be enclosed within the parentheses following the function name using the same order, number, and type as declared in the function prototype.

16 A First Book of ANSI C, Fourth Edition16 The items enclosed within the parentheses in the call statement, as we have seen, are called arguments of the function (see Figure 6.2). Other items used as synonyms for arguments are actual argument and actual parameters. findMax ( firstnum, secnum ); If a variable is one of the arguments in a function call, the called function receives a copy of the value stored in the variable.

17 A First Book of ANSI C, Fourth Edition17 For example, the statement maxnum = findMax(firstnum, secnum); calls the function findMax ( ), causes the values currently residing in the variables firstnum and secnum to be passed to findMax ( ), and assigns the function’s returned value to maxnum. The variable names in parentheses are actual arguments that provide values to the called function. After the values are passed, control is transferred to the called function.

18 A First Book of ANSI C, Fourth Edition18 As illustrated in Figure 6.3, the function findMax ( ) does not receive the variables named firstnum and secnum and has no knowledge of these variable names. The function simply receives copies of the values in these variables and must itself determine where to store these values before it does anything else.

19 A First Book of ANSI C, Fourth Edition19 The function gets a copy of the data to use. It may change its copy and, of course, change any variables declared inside itself. However, unless specific steps are taken to do so, a function is not allowed to change the contents of variables declared in other functions.

20 A First Book of ANSI C, Fourth Edition20 Function Header Line For example, the function header float findMax ( float x, float y) no semicolon declares the returned data type and name of the function as well as declaring the names and data types of all arguments. The argument names in the header line are formally referred to as parameters or formal arguments, and we shall use these terms interchangeably.

21 A First Book of ANSI C, Fourth Edition21 The function name and all parameter names in the header line, in this case findMax, x, and y, are chosen by the programmer. Any names selected according to the rules used to choose variable names can be used. All parameters listed in the function header line must be separated by commas and must have their individual data types specified separately. If a data type is omitted, the parameter, by default, is of type integer.

22 A First Book of ANSI C, Fourth Edition22 For example, the declarator findMax ( float x, y) does not declare both of the parameters, x and y, to be of type float; rather, it declares x to be of type float and y to be of type integer. Similarly, omitting the data type of the function immediately preceding the function’s name, by default, defines the function’s return value to be of type integer.

23 A First Book of ANSI C, Fourth Edition23 Thus both function headers int maxIt (float x, float y) and maxIt (float x, float y) define the function maxIt ( ) as returning an integer value.

24 A First Book of ANSI C, Fourth Edition24 Within a function header the keyword void is used to declare either that the function returns no value or has no arguments. For example, the function header void display ( int x, double y) declares that the function display ( ) returns no value, while the function header double printMessage (void) declares that the function printMessage ( ) has no parameters but returns a value of type double. As illustrated, a function header line is never terminated with a semicolon.

25 A First Book of ANSI C, Fourth Edition25 Thus, the complete function for the findMax( ) function is float findMax ( float x, float y ) /* function header */ { /* start of function body */ float maxnum; /* variable declaration */ if ( x >= y ) /* find the maximum number */ maxnum = x; else maxnum = y; return (maxnum); /* return the value */ } /* end of function definition */

26 A First Book of ANSI C, Fourth Edition26 When this function is called, the parameter x will be used to store the first value passed to it, and the parameter y will be used to store the second value passed at the time of the function call. The function itself will not know where the values come from when the call is made.

27 A First Book of ANSI C, Fourth Edition27 Note that within the return statement the data type of the returned variable correctly matches the data type in the function’s header line. It is up to the programmer to ensure that this is so for every function returning a value. Failure to match the return value with the function’s defined data type will not result in an error when your program is compiled, but it may lead to undesirable results,

28 A First Book of ANSI C, Fourth Edition28 As illustrated in Figure 6.7, the parameter x is used to store the first value passed to findMax ( ), and the parameter y is used to store the second value passed at the time of the function call. The findMax ( ) function does not know where the values come from when the call is made from main ( ).

29 A First Book of ANSI C, Fourth Edition29 Program 6.2 #include float findMax( float, float); /* the function prototype */ int main ( ) { float firstnum, secnum, maxnum; printf (“Enter a number:”); scanf (“%f”, &firstnum); printf (“\nGreat! Please enter a second number:”); scanf (“%f”, &secnum); maxnum = findMax ( firstnum, secnum); /* the function is called here */

30 A First Book of ANSI C, Fourth Edition30 printf (“\nThe maximum of the two numbers entered is %f ”,maxnum); return 0; } /* the following is the function findMax ( ) */ float findMax ( float x, float y ) /* function header */ { /* start of function body */ float maxnum; /* variable declaration */ if ( x >= y ) /* find the maximum number */ maxnum = x; else maxnum = y; return (maxnum); /* return the value */ } /* end of function definition */

31 A First Book of ANSI C, Fourth Edition31 In reviewing Program 6.2 it is important to note the four items we have introduced in this section. The first item is the function prototype ( declaration ) for findMax ( ). This statement, which ends with a semicolon as all statements do, alerts main ( ) to the data type that findMax ( ) will be returning and the number and the type of arguments that must be supplied to findMax ( ).

32 A First Book of ANSI C, Fourth Edition32 The second item to notice in main ( ) is the use of an assignment statement to call findMax ( ) and to store the returned value in the variable maxnum. We have also made sure to correctly declare maxnum as a floating point variable within main ( )’s variable declarations so that it matches the data type of the returned value.

33 A First Book of ANSI C, Fourth Edition33 The last two items to note concern the coding of the findMax ( ) function. The header line of findMax ( ) defines the function as returning a floating point value and declares the order, names, and data types of the arguments required by the function. Finally, the expression in the return statement evaluates to the correct return value data type defined in the function’s header line.

34 A First Book of ANSI C, Fourth Edition34 Thus, findMax ( ) is internally consistent in sending a floating point value back to any function that might be used to call it, and from the calling side, main ( ) has been correctly alerted to receive and use the returned value. In writing your own functions you must always keep these four items in mind. For another example, see if you can identify these four items in Program 6.3.

35 A First Book of ANSI C, Fourth Edition35 Program 6.3 #include double tempvert ( double ); /* function prototype */ int main ( ) { int count; /* start of declarations */ double fahren; for ( count = 1; count <= 4; ++count ) { printf (“Enter a Fahrenheit temperature: “); scanf (“%lf”, &fahren);

36 A First Book of ANSI C, Fourth Edition36 printf (“\nThe Celsius equivalent is %6.2f\n\n”, tempvert ( fahren)); } return 0; } double tempvert ( double inTemp ) /* function header */ { return ((5.0/9.0)*(inTemp -32.0)); }

37 A First Book of ANSI C, Fourth Edition37 Ends with a semicolon Does not end with a semicolon Function Header Line (continued)

38 A First Book of ANSI C, Fourth Edition38 Placement of Statements C does not impose a rigid statement ordering structure on the programmer. The general rule for placing statements in a program is simply that all preprocessor directives, variables, named constants, and functions ( except main ( ) ) must be either declared or defined before they can be used.

39 A First Book of ANSI C, Fourth Edition39 Placement of Statements Basic (good) programming structure: preprocessor directives symbolic constants function prototypes can be placed here int main() { function prototypes can be placed here variable declarations; other executable statements; return value; }

40 A First Book of ANSI C, Fourth Edition40 6.2 Returning a Value From its side of the return transaction, the called function must provide: –Data type of the returned value, which is specified in the function’s header line –Actual value being returned, which is specified by a return statement

41 A First Book of ANSI C, Fourth Edition41 Returning a Value (continue)

42 A First Book of ANSI C, Fourth Edition42 Returning a Value (continue) To return a value, use a return statement –return (expression); //or, return expression; –The expression is evaluated first; its value is then automatically converted to the return value’s data type as specified in the function’s header line before being sent back to the calling function Failure to exactly match the return value with the function’s declared data type can lead to undesired results –Return value is converted to the data type declared in the function’s header line

43 A First Book of ANSI C, Fourth Edition43 Returning a Value (continue)

44 A First Book of ANSI C, Fourth Edition44 Value is automatically converted from double to float (it may also generate a compiler warning message) printf("The Celsius equivalent is %5.2f\n", tempConvert(fahren)); Returning a Value (continue)

45 A First Book of ANSI C, Fourth Edition45 Function Stubs A stub is the beginning of a final function, used as a placeholder until the final function is completed float findMax(float x, float y) { printf("In findMax()\n"); printf("The value of x is %f\n", x); printf("The value of x is %f\n ", y); return 1.0; } A stub must compile and link with its calling module –Stub should display a message that it has been entered successfully and the value(s) of its received arguments

46 A First Book of ANSI C, Fourth Edition46 Functions with Empty Parameter Lists The prototype for a function with empty parameter list requires either writing the keyword void or nothing between the parentheses following the function’s name –int display(void); –int display(); A function with an empty parameter list is called by its name with nothing written in the parentheses following the function’s name –display();

47 A First Book of ANSI C, Fourth Edition47 Case Study: Calculating Age Norms

48 A First Book of ANSI C, Fourth Edition48 Requirements Specification A fairly common procedure in child development is to establish normal ranges for height and weight as they relate to a child’s age These normal ranges are frequently referred to as age norms In this case study, we develop a program for calculating both the expected height of a child between the ages of 6 and 11 and the deviation of this height norm to an actual child’s height

49 A First Book of ANSI C, Fourth Edition49 Requirements Specification (continued)

50 A First Book of ANSI C, Fourth Edition50 Requirements Specification (continued)

51 A First Book of ANSI C, Fourth Edition51 Requirements Specification (continued)

52 A First Book of ANSI C, Fourth Edition52 Requirements Specification (continued)

53 A First Book of ANSI C, Fourth Edition53 Requirements Specification (continued)

54 A First Book of ANSI C, Fourth Edition54 Requirements Specification (continued)

55 A First Book of ANSI C, Fourth Edition55 Standard Library Functions The standard library consists of 15 header files Before using these functions, you must know –The name of each available function –The arguments required by each function –The data type of the result (if any) returned by each function –A description of what each function does –How to include the library containing the desired function #include

56 A First Book of ANSI C, Fourth Edition56 Mathematical Library Functions

57 A First Book of ANSI C, Fourth Edition57 Mathematical Library Functions (continued)

58 A First Book of ANSI C, Fourth Edition58 The rand() and srand() Functions Random numbers are a series of numbers whose order cannot be predicted Pseudorandom numbers are not really random, but are sufficiently random for the task at hand All C compilers provide two functions for creating random numbers: rand() and srand(), defined in the stdlib.h header file –rand() produces random numbers in the range 0 < rand() < RAND_MAX –srand() provides a starting “seed” value for rand()

59 A First Book of ANSI C, Fourth Edition59 The rand() and srand() Functions (continued)

60 A First Book of ANSI C, Fourth Edition60 Scaling The method for adjusting the random numbers produced by a random-number generator to reside within a specified range is called scaling To scale a random number as an integer value between 1 and N: 1 + (int)rand() % N To produce a random integer between the numbers a and b : a + (int)(rand() % (b - a + 1))

61 A First Book of ANSI C, Fourth Edition61 Coin Toss Simulation

62 A First Book of ANSI C, Fourth Edition62 Coin Toss Simulation (continued)

63 A First Book of ANSI C, Fourth Edition63 Coin Toss Simulation (continued)

64 A First Book of ANSI C, Fourth Edition64 Input/Output Library Functions getchar() can be used for single character input –int getchar() –The reason for returning characters in integer format is to allow the End-Of-File (EOF) sentinel to be returned putchar() expects a single character argument and displays the character passed to it on the terminal –For example, putchar('a')

65 A First Book of ANSI C, Fourth Edition65 Character Processing Functions

66 A First Book of ANSI C, Fourth Edition66 Character Processing Functions (continued)

67 A First Book of ANSI C, Fourth Edition67 Character Processing Functions (continued)

68 A First Book of ANSI C, Fourth Edition68 Conversion Functions

69 A First Book of ANSI C, Fourth Edition69 Conversion Functions (continued)

70 A First Book of ANSI C, Fourth Edition70 Common Programming Errors Passing incorrect data types Omitting a called function’s prototype Terminating a function’s header line with a semicolon Forgetting to include a data type for each parameter listed in a function’s header line Returning a different data type from a function than the data type specified in the function’s header line

71 A First Book of ANSI C, Fourth Edition71 Common Compiler Errors

72 A First Book of ANSI C, Fourth Edition72 Common Compiler Errors (continued)

73 A First Book of ANSI C, Fourth Edition73 Summary A function is called by giving its name and passing any data to it in the parentheses following the name The first line of the function is called the function header A function’s return type is the data type of the value returned by the function Functions can directly return at most a single value to their calling functions

74 A First Book of ANSI C, Fourth Edition74 Summary (continued) Functions can be declared to all calling functions with a function prototype Arguments passed to a function provide a means of evaluating any valid C expression A set of preprogrammed functions for mathematical calculations, character input and output, character processing, and numerical conversions are included in the standard library provided with each C compiler


Download ppt "A First Book of ANSI C Fourth Edition Chapter 6 Modularity Using Functions: Part I."

Similar presentations


Ads by Google