Chapter 4: Functions Introduction to Function
Objectives To construct programs modularly from functions. To use common math functions available in the C Standard Library. To create functions with multiple parameters. The mechanisms for passing information between functions and returning results. How the function call/return mechanism is supported by the function call stack and activation records. To write and use recursive functions.
Intro Divide and conquer. Use for various individual tasks. Functions enable grouping of commonly used code into a reusable and compact unit. In this chapter we will see  how functions are defined and how they are accessed from various places within a C program.  Overview of function, and a portion of the C Standard Library functions.  learn how to declare a function, and the manner in which information is passed to a function.
Intro Advantages of using functions avoids the need for redundant (repeated) programming of the same instructions.  easier to write and easier to debug.  logical structure is more apparent than programs which lack this type of structure, especially true of lengthy, complicated programs.  avoids repetitive programming between programs
Function Overview Every C program consists of one or more functions.  One of these functions must be called  main .  A function will carry out its intended action whenever it is  accessed  or  called  from some other portion of the program.  The same function can be accessed from several different places within a program.  Once the function has carried out its intended action, control will be returned to the point from which the function was accessed.
Function Overview Two type of functions Library functions used to carry out a number of commonly used operations such as  printf(…) ,  getchar(),   and  putchar(). User/Programmer-defined functions used to define their own functions for carrying out various individual tasks.  Information is passed to the function via special identifiers called  arguments  (also called parameters), and returned via the return statement.
Library Functions 4 categories: Library functions that carry out standard I/O operations  (e.g., read and write characters, and numbers, etc.). Functions that perform operations on characters  (e.g., convert from lower- to uppercase, test for end of file, etc.).  Functions that perform operations on strings  (e.g., copy a strings, compare strings, concatenate strings, etc.). Functions that carry out various mathematical calculations  (e.g. evaluate trigonometric, logarithmic and exponential functions,, etc.).
Library Functions 3 types of library functions: return a data item to their access point. indicate whether a condition is true or false by returning a 1 or a 0,  carry out specific operations on data items but do not return anything.
Library Functions:  Standard Library Header Description <stdio.h> Functions  for standard input and output <float.h> Floating point size limits <limits.h> Contains integral size limits of system <stdlib.h> Functions for converting numbers to text and text to numbers, memory allocation, random numbers, other utility functions <math.h> Math library functions <string.h> String processing functions <stddef.h> Common definitions of types used by C
Library Functions:  Math.h Functions Function Returns sqrt(x) Square root exp(x) Exponential function  log(x) Natural logarithm (base e) log10(x) Logarithm (base 10) fabs(x) Absolute value pow(x,y) X raised to the power of y sin(x) Trignometric sine (x in radians) cos(x) Trignometric cosine (x in radians) tan(x) Trignometric tangent (x in radians) atan(x) Arctangent of x (returned value is in radians)
Using Functions Include the header file for the required library using the preprocessor directive #include <libraryname.h> Note: no semi colon after this Variables defined in functions are local variables Functions have a list of parameters Means of communicating information between functions Functions can return values printf and scanf good examples of function calls
User-defined Functions:  Function Definition A function definition has two principal components:  the  first line  (including the argument declarations), and  the  body  of the function. The  first line  of a function definition contains the type specification of the value returned by the function followed by the function name, and  (optionally) a set of arguments, separated by commas and enclosed in parentheses.
User-defined functions:  Function Definition Format of a function definition Return-value-type function-name(parameter-list) { declarations statements } A return value of type  void  indicates a function does not Return a value.
User-defined Functions:  Function Definition Function Definition: argument/parameter The arguments are called  formal argument because they represent the names of data items that are transferred into the function from the calling portion of the program.  There are also known as parameters or formal parameters.  The identifiers used as formal arguments are “local”  because they are not recognized outside of the function.  the names need not to be same as the names of the actual arguments in the calling portion of the program.
User-defined Functions:  Function Definition Function Definition: compound statement/body compound statement that defines the action to be taken by the function.  can contain expression statements, other compound statements, control statements, and so on.  It should include one or more  return  statements, in order to return a value to the calling portion of the program.
User-defined Functions:  Function Definition Function definition: return Return control to point from which function called 3 Ways to return Function does not return a result (void) control is returned when function right brace } is reached. Execute the statement return; If the statement returns a value the following statement must be executed return expression;
User-defined Functions:  Example Function prototype & definition #include <stdio.h> int mod(int, int);  /* Function Prototype */ main() { printf(&quot;The mod is: %d &quot;, mod(4,5)); } /* Function Definition */ int mod(int x, int y) { return x % y; }
User-defined Functions:  Example Function with definition but without prototype #include <stdio.h> int sum(int x, int y)  /* Function Definition */ { return x+y; } main() { printf(&quot;The sum is: %d &quot;,  sum(4,5)); }
User-defined Functions:  Function Prototype The function prototype Very important feature. Must be added to a C program before the main function, if call that function before defining it. It tells the compiler what type of value the function returns, number and types of parameters, and order in which these parameters are expected. There is no need for a prototype if the function is called after its definition.
User-defined Functions:  Function Prototype Example function prototype long int sum (int x, int y); Where; x & y  - Parameters int  - Parameter type sum  - Function name long int  - Function return type
User-defined Functions:  Function Calls A function can be accessed (i.e.,   called ) by specifying its name, followed by a list of arguments enclosed in parentheses and separated by commas.  If the function call does not require any arguments empty pair of parentheses must follow the name of the function. The arguments appearing in the function call are referred to as  actual arguments , in contrast to the formal arguments that appear in the first line of the function definition.
User-defined Functions:  Function Calls In a normal function call there will be one actual argument for each formal argument.  may be expressed as  constants, single variables , or more complex expressions. If the function returns a value, the function access is written a statement; e.g.,  y = sum(x); if the function does not return anything, the function access appears by itself; e.g.,  view(a,b,c);
User-defined Functions:  Function Calls A function can be called by  the main function other functions itself (recursion) In C, functions calls can be by value by reference
User-defined Functions:  Function Calls Call by value Copy of variable passed to function If that variable is modified within the function then upon return from the function since only the copy has been modified, the actual variable is not modified Call by reference Pass the address of a variable (i.e. a pointer) to a function The variable pointed to can be modified within that function
User-defined Functions:  Function Calls Example Call By Value finval=FuncByValue(finval);  The FuncByValue function float  FuncByValue(float fval) { return fval*fval; }
User-defined Functions:  Function Calls Example By Reference FuncByReference(&finref),   Use & to pass the address of a variable to the function;  The FuncByReference function Value of the referenced variable passed to the function is modified after returning from the function. void  FuncByReference(float *fvalptr) { *fvalptr = *fvalptr * *fvalptr; }
User-defined Functions:  Recursion A function calls itself repeatedly, until some specified condition has been satisfied.  Each action is stated in terms of a previous result.  Many iterative (i.e., repetitive) problems can be written in this form. In order to solve a problem recursively, two conditions must be satisfied.  the problem must be written in recursive form. the problem statement must include a stopping condition.
User-defined Functions:  Recursion Example Factorial long int factorial (int n) /* calculate the factorial of n */ { if (n <= 1) return(1); else return(n *  factorial(n-1) ); }
Additional Info:  Header Files Standard libraries have header files containing function prototypes for all functions in that library Programmer can create custom header files Should end in  .h  e.g.  myfunctionlib.h Programmer function prototypes declared using the pre processor directive #include “myfunctionlib.h”
Tuliskan satu fungsi takrifan pengguna yang diberi nama  kuasa( ).  Fungsi ini menerima input dua nombor integer iaitu x dan n, dan seterusnya mengira x n   tanpa  menggunakan fungsi pow(x,n). Kembalikan nilai tadi kepada fungsi yang memanggil  Tuliskan satu cara untuk menggunakan/memanggil fungsi  kuasa( )  di atas.
Tulis satu fungsi dalam bahasa C untuk  luas_bulatan( )  yang menerima argumen berjenis float iaitu jejari kepada bulatan, kemudian mengira luas bulatan dan seterusnya mengembalikan luas bulatan tersebut kepada fungsi pemanggil.  Tuliskan satu cara untuk menggunakan/memanggil fungsi  luas_bulatan( )  di atas.
Based on the following function, write the function calls and prototype function for that function when x = 4.2 and y = 2.1. Then write the output. void printresults( float x, float y) { float num1, num2; num1 = x; num2 = y; printf(“Result of add the value = %.2f”, num1+num2); printf(“Result of multiply the value = %.2f”, num1*num2); }
Based on the following function: float calculate_dividen(float saving) { float dividen; dividen = saving * 0.16; return (dividen); } Write an example of function calls. What is the prototype of this function?
What is the first line syntax of function definition of the following statement? A function called maximum accepts three integers (x, y, and z) and returns integer A. maximum (int, int, int) B. maximum (x, y, z) C. int maximum (x, y, z) D. int maximum (int x, int y, int z)
What is the output for the following C program if the entered input is 108? #include<stdio.h> void final_value(int z) { int a = 5; while ( z > 0) { a++; z /=10; } printf(“ Final value of z = %d and a = %d\n”, z, a); } main( ) { int x, y = 0; printf(“\n Enter one integer value: “); scanf (“%d”, &x); final_value(x); }
Which one of the following is the correct function call for function xyz? call xyz( ); void xyz(void); xyz; p = xyz( );
What is the correct function prototype for the following statement? A function called  Average  accepts two float arguments (a and b) and print the average of a and b. float Average (a, b); void Average (a, b); void Average (float, float); float Average (float float);
Contoh Setempat void main() { int i, j; : : } void fungsi() { : : } Sejagat int i, j; void main(void) { : : } void fungsi1() { : : }
#include <stdio.h> int i, j; void fungsi1(); void main() { fungsi1(); printf(&quot;Main: i = %d, j = %d\n&quot;, i, j); } void fungsi1() { i = 1000; j = 500; printf(“Fungsi1: i = %d, j = %d\n&quot;, i, j); }
#include <stdio.h> void fungsi1(); void main() { int i = 1000; printf(&quot;Main: i = %d\n&quot;, i); fungsi1(); printf(&quot;Main lagi: i = %d\n&quot;, i); } void fungsi1() { int i = 500; printf(&quot;Fungsi1: i = %d\n&quot;, i); }
#include <stdio.h> void fungsi1(int); void main() { int i = 1000; fungsi1(i); printf(&quot;Main: i = %d\n&quot;, i); } void fungsi1(int j) { j = 5 * j; printf(&quot;Fungsi1: j = %d\n&quot;, j); }

Ch4 functions

  • 1.
    Chapter 4: FunctionsIntroduction to Function
  • 2.
    Objectives To constructprograms modularly from functions. To use common math functions available in the C Standard Library. To create functions with multiple parameters. The mechanisms for passing information between functions and returning results. How the function call/return mechanism is supported by the function call stack and activation records. To write and use recursive functions.
  • 3.
    Intro Divide andconquer. Use for various individual tasks. Functions enable grouping of commonly used code into a reusable and compact unit. In this chapter we will see how functions are defined and how they are accessed from various places within a C program. Overview of function, and a portion of the C Standard Library functions. learn how to declare a function, and the manner in which information is passed to a function.
  • 4.
    Intro Advantages ofusing functions avoids the need for redundant (repeated) programming of the same instructions. easier to write and easier to debug. logical structure is more apparent than programs which lack this type of structure, especially true of lengthy, complicated programs. avoids repetitive programming between programs
  • 5.
    Function Overview EveryC program consists of one or more functions. One of these functions must be called main . A function will carry out its intended action whenever it is accessed or called from some other portion of the program. The same function can be accessed from several different places within a program. Once the function has carried out its intended action, control will be returned to the point from which the function was accessed.
  • 6.
    Function Overview Twotype of functions Library functions used to carry out a number of commonly used operations such as printf(…) , getchar(), and putchar(). User/Programmer-defined functions used to define their own functions for carrying out various individual tasks. Information is passed to the function via special identifiers called arguments (also called parameters), and returned via the return statement.
  • 7.
    Library Functions 4categories: Library functions that carry out standard I/O operations (e.g., read and write characters, and numbers, etc.). Functions that perform operations on characters (e.g., convert from lower- to uppercase, test for end of file, etc.). Functions that perform operations on strings (e.g., copy a strings, compare strings, concatenate strings, etc.). Functions that carry out various mathematical calculations (e.g. evaluate trigonometric, logarithmic and exponential functions,, etc.).
  • 8.
    Library Functions 3types of library functions: return a data item to their access point. indicate whether a condition is true or false by returning a 1 or a 0, carry out specific operations on data items but do not return anything.
  • 9.
    Library Functions: Standard Library Header Description <stdio.h> Functions for standard input and output <float.h> Floating point size limits <limits.h> Contains integral size limits of system <stdlib.h> Functions for converting numbers to text and text to numbers, memory allocation, random numbers, other utility functions <math.h> Math library functions <string.h> String processing functions <stddef.h> Common definitions of types used by C
  • 10.
    Library Functions: Math.h Functions Function Returns sqrt(x) Square root exp(x) Exponential function log(x) Natural logarithm (base e) log10(x) Logarithm (base 10) fabs(x) Absolute value pow(x,y) X raised to the power of y sin(x) Trignometric sine (x in radians) cos(x) Trignometric cosine (x in radians) tan(x) Trignometric tangent (x in radians) atan(x) Arctangent of x (returned value is in radians)
  • 11.
    Using Functions Includethe header file for the required library using the preprocessor directive #include <libraryname.h> Note: no semi colon after this Variables defined in functions are local variables Functions have a list of parameters Means of communicating information between functions Functions can return values printf and scanf good examples of function calls
  • 12.
    User-defined Functions: Function Definition A function definition has two principal components: the first line (including the argument declarations), and the body of the function. The first line of a function definition contains the type specification of the value returned by the function followed by the function name, and (optionally) a set of arguments, separated by commas and enclosed in parentheses.
  • 13.
    User-defined functions: Function Definition Format of a function definition Return-value-type function-name(parameter-list) { declarations statements } A return value of type void indicates a function does not Return a value.
  • 14.
    User-defined Functions: Function Definition Function Definition: argument/parameter The arguments are called formal argument because they represent the names of data items that are transferred into the function from the calling portion of the program. There are also known as parameters or formal parameters. The identifiers used as formal arguments are “local” because they are not recognized outside of the function. the names need not to be same as the names of the actual arguments in the calling portion of the program.
  • 15.
    User-defined Functions: Function Definition Function Definition: compound statement/body compound statement that defines the action to be taken by the function. can contain expression statements, other compound statements, control statements, and so on. It should include one or more return statements, in order to return a value to the calling portion of the program.
  • 16.
    User-defined Functions: Function Definition Function definition: return Return control to point from which function called 3 Ways to return Function does not return a result (void) control is returned when function right brace } is reached. Execute the statement return; If the statement returns a value the following statement must be executed return expression;
  • 17.
    User-defined Functions: Example Function prototype & definition #include <stdio.h> int mod(int, int); /* Function Prototype */ main() { printf(&quot;The mod is: %d &quot;, mod(4,5)); } /* Function Definition */ int mod(int x, int y) { return x % y; }
  • 18.
    User-defined Functions: Example Function with definition but without prototype #include <stdio.h> int sum(int x, int y) /* Function Definition */ { return x+y; } main() { printf(&quot;The sum is: %d &quot;, sum(4,5)); }
  • 19.
    User-defined Functions: Function Prototype The function prototype Very important feature. Must be added to a C program before the main function, if call that function before defining it. It tells the compiler what type of value the function returns, number and types of parameters, and order in which these parameters are expected. There is no need for a prototype if the function is called after its definition.
  • 20.
    User-defined Functions: Function Prototype Example function prototype long int sum (int x, int y); Where; x & y - Parameters int - Parameter type sum - Function name long int - Function return type
  • 21.
    User-defined Functions: Function Calls A function can be accessed (i.e., called ) by specifying its name, followed by a list of arguments enclosed in parentheses and separated by commas. If the function call does not require any arguments empty pair of parentheses must follow the name of the function. The arguments appearing in the function call are referred to as actual arguments , in contrast to the formal arguments that appear in the first line of the function definition.
  • 22.
    User-defined Functions: Function Calls In a normal function call there will be one actual argument for each formal argument. may be expressed as constants, single variables , or more complex expressions. If the function returns a value, the function access is written a statement; e.g., y = sum(x); if the function does not return anything, the function access appears by itself; e.g., view(a,b,c);
  • 23.
    User-defined Functions: Function Calls A function can be called by the main function other functions itself (recursion) In C, functions calls can be by value by reference
  • 24.
    User-defined Functions: Function Calls Call by value Copy of variable passed to function If that variable is modified within the function then upon return from the function since only the copy has been modified, the actual variable is not modified Call by reference Pass the address of a variable (i.e. a pointer) to a function The variable pointed to can be modified within that function
  • 25.
    User-defined Functions: Function Calls Example Call By Value finval=FuncByValue(finval); The FuncByValue function float FuncByValue(float fval) { return fval*fval; }
  • 26.
    User-defined Functions: Function Calls Example By Reference FuncByReference(&finref), Use & to pass the address of a variable to the function; The FuncByReference function Value of the referenced variable passed to the function is modified after returning from the function. void FuncByReference(float *fvalptr) { *fvalptr = *fvalptr * *fvalptr; }
  • 27.
    User-defined Functions: Recursion A function calls itself repeatedly, until some specified condition has been satisfied. Each action is stated in terms of a previous result. Many iterative (i.e., repetitive) problems can be written in this form. In order to solve a problem recursively, two conditions must be satisfied. the problem must be written in recursive form. the problem statement must include a stopping condition.
  • 28.
    User-defined Functions: Recursion Example Factorial long int factorial (int n) /* calculate the factorial of n */ { if (n <= 1) return(1); else return(n * factorial(n-1) ); }
  • 29.
    Additional Info: Header Files Standard libraries have header files containing function prototypes for all functions in that library Programmer can create custom header files Should end in .h e.g. myfunctionlib.h Programmer function prototypes declared using the pre processor directive #include “myfunctionlib.h”
  • 30.
    Tuliskan satu fungsitakrifan pengguna yang diberi nama kuasa( ). Fungsi ini menerima input dua nombor integer iaitu x dan n, dan seterusnya mengira x n tanpa menggunakan fungsi pow(x,n). Kembalikan nilai tadi kepada fungsi yang memanggil Tuliskan satu cara untuk menggunakan/memanggil fungsi kuasa( ) di atas.
  • 31.
    Tulis satu fungsidalam bahasa C untuk luas_bulatan( ) yang menerima argumen berjenis float iaitu jejari kepada bulatan, kemudian mengira luas bulatan dan seterusnya mengembalikan luas bulatan tersebut kepada fungsi pemanggil. Tuliskan satu cara untuk menggunakan/memanggil fungsi luas_bulatan( ) di atas.
  • 32.
    Based on thefollowing function, write the function calls and prototype function for that function when x = 4.2 and y = 2.1. Then write the output. void printresults( float x, float y) { float num1, num2; num1 = x; num2 = y; printf(“Result of add the value = %.2f”, num1+num2); printf(“Result of multiply the value = %.2f”, num1*num2); }
  • 33.
    Based on thefollowing function: float calculate_dividen(float saving) { float dividen; dividen = saving * 0.16; return (dividen); } Write an example of function calls. What is the prototype of this function?
  • 34.
    What is thefirst line syntax of function definition of the following statement? A function called maximum accepts three integers (x, y, and z) and returns integer A. maximum (int, int, int) B. maximum (x, y, z) C. int maximum (x, y, z) D. int maximum (int x, int y, int z)
  • 35.
    What is theoutput for the following C program if the entered input is 108? #include<stdio.h> void final_value(int z) { int a = 5; while ( z > 0) { a++; z /=10; } printf(“ Final value of z = %d and a = %d\n”, z, a); } main( ) { int x, y = 0; printf(“\n Enter one integer value: “); scanf (“%d”, &x); final_value(x); }
  • 36.
    Which one ofthe following is the correct function call for function xyz? call xyz( ); void xyz(void); xyz; p = xyz( );
  • 37.
    What is thecorrect function prototype for the following statement? A function called Average accepts two float arguments (a and b) and print the average of a and b. float Average (a, b); void Average (a, b); void Average (float, float); float Average (float float);
  • 38.
    Contoh Setempat voidmain() { int i, j; : : } void fungsi() { : : } Sejagat int i, j; void main(void) { : : } void fungsi1() { : : }
  • 39.
    #include <stdio.h> inti, j; void fungsi1(); void main() { fungsi1(); printf(&quot;Main: i = %d, j = %d\n&quot;, i, j); } void fungsi1() { i = 1000; j = 500; printf(“Fungsi1: i = %d, j = %d\n&quot;, i, j); }
  • 40.
    #include <stdio.h> voidfungsi1(); void main() { int i = 1000; printf(&quot;Main: i = %d\n&quot;, i); fungsi1(); printf(&quot;Main lagi: i = %d\n&quot;, i); } void fungsi1() { int i = 500; printf(&quot;Fungsi1: i = %d\n&quot;, i); }
  • 41.
    #include <stdio.h> voidfungsi1(int); void main() { int i = 1000; fungsi1(i); printf(&quot;Main: i = %d\n&quot;, i); } void fungsi1(int j) { j = 5 * j; printf(&quot;Fungsi1: j = %d\n&quot;, j); }