Chapter 5 Modular Design and Function C Programming for Scientists & Engineers with Applications by Reddy & Ziegler
5.1 Introduction to Modular Programming Design of Modular Programs The design of modular programs is a top-down methodology where the top module is the statement of the problem. Functional Modules in C Functions are logical pieces of code that can be compiled, executed, and tested before being integrated incrementally into the program.
5.2 Functions Differences between a C program with just one function (main) and a program with many functions New issues in your programming Planning Create a structure chart and data flow diagram Lay out exactly how the functions are to be connected together Table 5.1
Functions Program with single function Program with many functions Connection Information transferring is not a issue The information passed between functions is critical Planning Require planningThe program must be thoroughly planned. Errors To correct an error may mean changing many locations of the program An error in one function may require correcting the error in just that one function. Reusability Modification may be necessaryCan be copied and used in other programs that require similar tasks.
Topics Function prototypes Function types Function definitions Transferring values to functions Types of functions Similarities between functions and variables in C Function names and variable names are considered to be identifiers Functions have types associated with them Must be declared prior to their use
Categories of Functions Functions Library functions Programmer-defined functions Math I/O others Functions that return nothing Functions that return one value Functions that return more than one value
Functions That Do Not Return a Value How do we call a function? Write the function name followed by arguments enclosed in parentheses. Ex: function2(m,y); What does a function call do? Transfer program control to the function function1(); printf(“…”); The control in main goes to function1
Direction of program flow main main { function call function call … … } function1 function1 { … … }
A Major Issue What is a major issue in writing programs with functions? What is a major issue in writing programs with functions? Correctly transferring information between the two functions involved Correctly transferring information between the two functions involved Pass to a function only the needed information Pass to a function only the needed information Help control the extend of errors Help control the extend of errors Determine information should be passed to a function and to pass it correctly. Determine what information should be passed to a function and how to pass it correctly. Require considerable advance planning Require considerable advance planning
Types of Functions What types of functions are there? int long int float double long double char void
5.2 Functions Function Declaration Function Definition Scope of Names return Statement
A function is a piece of code that performs a specific task. A function is activated (i.e., invoked, called) by the main function or by another function. The data types, the order, and the number of arguments passed from the calling program must match the parameters of the called function declaration (or prototype) and the header of the function definition. A function name appears in at least three places in the code. The function name needs to appear in the following order: 1. The function prototype: type func (type list). 2. The function call: func (arg list). 3. The function definition: type func (parameter list) { return }
Function Declaration
Function Definition
Passing Information Have we passed any information from main to function1 or function2? function1( ); No variable values are passed from main to function1() function2(m,y); We are passing from main to function2 the values of the variables m and y. In main, at the location of the call to function2, the value of m is 15 and the value of y is function2 receives the value 15 and
Passing Information Where does function2 store these values? function2(m, y); void function2(int n, double x) The value of m in main is assigned to n in function2; the value of y in main is assigned to x in function2. Work with the variables n and x to calculate other things of interest.
Programmer-define Function How to define a programmer-define function? A function prototype A function definition A function call What is a function prototype? Indicates that a function exists and probably will be used in the program r_type f_name (arg_type arg_name, arg_type arg_name, …) arg_type: argument type (int, double, …) arg_name: a valid identifier f_name: the function name r_type: the value type returned by the function
Function Prototype The primary purpose of a function prototype Establish the type of arguments for a function to receive The order in which it is to receive them void function2(int n, double x); Need semicolon at the end of the function prototype Return no values r_type f_name (arg_type, arg_type, arg_type, … ); void function2( int, double);
Function Definition A function definition r_type f_name (arg_type arg_name, arg_type arg_name, …) { … function_body – C declaration and statements … } No semicolon ends the line containing the function name and arguments Function declaration (function header)
Function Call A function call consists of a function name followed by an argument-expression list enclosed in parentheses. f_name (exp, exp, …); exp can be a single variable or constant … represents more comma-separated expressions (exp, exp, …) is called the argument list The argument list represents the value passed from the function in which the call exists to the function being called. function2(m, y); the call to function2 in main Cause m and y to be passed from main to function2
Number, Order, and Type What about the number, order, and type of parameters in the argument lists of a function call and its definition? These must match. Referred to by the acronym NOT (number, order, type). Prototype void function2(int n, double x); Function header void function2(int n, double x) Function call function2(m, y);
Functions Avoid errors caused by order Make your variable names very descriptive Use good commenting (use a banner) Is it necessary to have main as the first function defined? (No!) #include… void function1(void); void function2(int n, double x); void function1(void) { function body } void function2(int n, double x) { function body } void main(void) { function body }
Functions Is there any relationship between the variable m in main and the variable m in function2? No! Variable names are declared for each function. No connection between those two variables. The only connections between functions occur through the argument list.
#include void function1(void); void function2(int n, double x); void main(void) { int m; double y ; m=15; y=308.24; printf ("The value of m in main is m=%d\n\n",m); function1( ); function2(m,y); printf ("The value of m in main is still m=%d\n",m); } Source Code L5-1.C Function prototypes Calls to function1 and function2
void function1(void) { printf("function1 is a void function that does not receive\n\ \rvalues from main.\n\n"); } void function2(int n, double x) { int k,m; double z; k=2*n+2; m=5*n+37; z=4.0*x-58.4; printf("function2 is a void function that does receive\n\ \rvalues from main. The values received from main are:\n\ \r\t n=%d \n\r\t x=%lf\n\n",n,x); printf("function2 creates three new variables, k, m and z\n\ \rThese variables have the values:\n\ \r\t l=%d \n\r\t m=%d \n\r\t z=%lf\n\n",k,m,z); } Function header Definition of function2
Functions that return one value (Lesson 5.2) How do we define a function that returns a single value? In its prototype and declarator, a function must have a type that reflects the type of value returned. unsigned long int fact(int m); return (product); return (expression); Jump statements return statement break statement
The Transfer of Information (Figure 5.5) main { … g = fact(n) … } fact(int m) for(…) { product … } return(product)
Return statement Can we use a return statement in a void function? Yes! (must not use an expression with it) return; How does control transfer back to the calling function without using a return statement? Reaching the } terminates a function Equivalent to “return;”
Return statement The locations of a return statement Can appear anywhere in the function body A common structure if (expression) { return(a); } else { return(b); }
Return statement The type int is used for main. What does this do? Can return an int value to its calling function The calling “function” for main is the operating system Return 0 to the OS, which the OS interprets as meaning that the program has terminated normally.
Source Code L5_2.C /* Program for Lesson 5_2*/ #include unsigned long int fact(int m); int main(void) { int n; unsigned long int g; double one_over_nfactorial; printf("This program calculates 1/nfactorial.\n\ \rEnter a positive integer less than or equal to 12:\n "); scanf ("%d",&n); g=fact(n); one_over_nfactorial=1.0/g; printf("1/%d! = %e",n,one_over_nfactorial); return (0); } Function prototype Use type int for main Call fact and assign the return value to g Return an int type from main to the OS
Source Code L5_2.C unsigned long int fact(int m) { int i; unsigned long int product; product = 1; for (i=m; i>=1; i--) { product*=i; } return(product); } Function declarator. The variable m contains the value of n passed from main Definition of function fact
Scope What is meant by scope? Scope refers to the region in which a declaration is active. Four kinds of scope Block Function File Prototype Scope for an identifier is determined by the location of the identifier’s declaration. Example: source code L5_3.C
/* Program for Lesson 5_3 */ #include int m = 12; int function1 (int a, int b, int c, int d); void main(void) { int n = 30; int e,f,g,h,i; e=1; f=2; g=3; h=4; printf ("\n\n In main (before the call to function1): \n\ \r m = %d\n\ \r n = %d\n\ \r e = %d\n\n",m,n,e ); i=function1(e,f,g,h); printf ("After returning to main: \n"); printf ("n = %d \n\ \r m = %d \n\ \r e = %d \n\ \r i = %d", n, m,e,i); } The variable n has function scope; therefore, n in main has no connection to n in function1. Declaring the variable m outside any function definition gives the variable file scope. A variable with file scope is generally called a global variable. Prototype for function1 Does not need to be initialized Call to function1 The variable m has been modified by function1.
int function1 (int a, int b, int c, int d) { int n = 400; printf ("In function1:\n\ \r n = %d\n\ \r m = %d initially\n\ \r a = %d initially \n",n,m,a); m = 999; if (a>=1) { a+=b+m+n; printf ("m = %d after being modified\n\ \r a = %d after being modified\n\n",m,a) ; return (a); } else { c+=d+m+n; return (c); } The variable n has function scope The variable of the global variable m is modified with this statement. A function may have more than one return statement. However, only one is executed.
Scope Function scope The variable assigned is valid only within the function in which it was defined. The variable n File scope The identifier function1 The prototype for function1 is outside the body of any function. From the point of declaration to the end of the file. The variable m; #define P 200 Block scope A block of code begins with { and ends with }. Function prototype scope Parameters given names in function prototypes have function prototype scope
Passing Values to Functions How to pass the arguments through an argument list? When a function called, C allocates space within memory for the variables in the function’s parameter list and the variable declared in the function body. Copy the values of the expressions in the function call into the locations of the corresponding variables within the region allocated to the function. Fig. 5.6
Figure 5.6
The Passing of Information What happen when the value a is returned from function1 to main? i = function1(e, f, g, h); The return value a from function1 is assigned to the value i in main. Figure 5.7 Figure 5.8
Figure 5.7
Figure 5.8
Variables and Parameters What are local and global variables? Global variables are variables with file scope. Local variables are variables with function scope. m is a global variable. n is a local variable. What are formal and actual parameters? Formal parameters refer to the parameters listed in the function prototype and function definition. Actual parameters are parameters in the parameter list of the function call.
The Memory Space What happens to the memory space allocated to the variables in function1 in this lesson’s program after the execution has finished? The space is freed up. Each time a function is called, memory is reserved; unless otherwise specified, when the function finished executing, the memory is freed.
Scope of Names
return Statement
5.3 Computation Functions Passing Arguments by Value Passing Arguments by Pointer
Computation Functions A function which calls another function is called a calling function or invoking function. A function that is called is a called function, or invoked function. The information passed by the calling function to the called function is passed through arguments. The information received by the called function from the calling function is received by parameters.. The arguments and parameters must match in their data types, order, and number.
Passing Arguments by Value
Passing Arguments by Pointer
Input and Output Functions An input function should check for invalid data and control characters such as end-of-file. It should return a status flag through the return statement, and return valid input through the parameter list. Global variables should not be used An input function should check for invalid data and control characters such as end-of-file. It should return a status flag through the return statement, and return valid input through the parameter list. Global variables should not be used There are several ways of handling an input data file. The file pointer can be declared global, in which case, the file is opened in the main function before the input function is called. Or the file pointer can be local to the main function, in which case the file is opened there. Or the file pointer can be both declared and opened local to the input function. There are several ways of handling an input data file. The file pointer can be declared global, in which case, the file is opened in the main function before the input function is called. Or the file pointer can be local to the main function, in which case the file is opened there. Or the file pointer can be both declared and opened local to the input function.
5.4 Input and Output Functions Input Using Functions Input Using Functions Output Using Functions Output Using Functions
Input Using Functions
Output Using Functions
Recursive Functions A recursive function is one that calls itself. The declaration and definition of recursive functions is similar to the declaration and definition of regular C functions. The calling function transfers control to the recursive function. After completion, the recursive function returns control to the calling function. As every function must terminate execution, a recursive function begins with a check for the terminating condition.
5.5 Recursive Functions Concept of Recursion Relationship between Integration and Recursion
Concept of Recursion
Relationship between Integration and Recursion
5.6 Sample Programs Rocket Motor Thrust Rocket Motor Thrust Current in Series Circuit Current in Series Circuit Square Root Function Square Root Function