1 / 49

Lecture 6 – Functions

Lecture 6 – Functions. Lecture Outline. Why use functions? Functions in C Pre-defined functions User-defined functions Function Prototype, Definition, Call Functions that return a value Functions that do not return a value Global Variable vs. Local Variable

rosass
Download Presentation

Lecture 6 – Functions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Lecture 6 – Functions

  2. Lecture Outline • Why use functions? • Functions in C • Pre-defined functions • User-defined functions • Function Prototype, Definition, Call • Functions that return a value • Functions that do not return a value • Global Variable vs. Local Variable • Pass by Value vs. Pass by Reference • Recursive Functions & its applications • Sample Applications

  3. What are functions? • Divide and conquer • Construct a large program from smaller pieces called modules • Modules in C language are called functions • Two types of functions • C standard library • Functions written by programmers

  4. Why use functions? • Let say you want to print one row of number 8 and one row of number 9 • What is the output????? #include <stdio.h> int main() { int i, j; //print one row of number 8 for(i=1; i<=10; i++) printf(“8"); printf("\n"); //go to new line //print one row of number 9 for(j=1; j<=10; j++) printf(“9“); printf("\n"); //go to new line return 0; }

  5. Why use functions?(cont) • It seems that you are doing the same thing twice!!(i.e. printing two rows of numbers) • This is wasting time and not flexible!! • So need to use function

  6. Why use functions?(cont) #include <stdio.h> void display(int); //function prototype int main() { display(8); //function call display(9); //function call return 0; } void display(int value) //function definition { int i; for(i=1; i<=10; i++) printf("%d", value); printf("\n"); //go to new line }

  7. Functions in C • Functions can be created to execute small, frequently-used tasks • In C, there are predefined functions or sometimes called standard functions, and there are user-defined functions. • Predefined functions are already available functions & can be used, called library • The usage is like stdio.h, in which the library name must be #included at the top of the source code (preprocessor directive)

  8. Predefined function (Library) • Common libraries are stdio.h, math.h, string.h, and stdlib.h • stdio.h related functions: printf, scanf,etc • math.h related functions: sin, cos, exp, pow, sqrt, etc. • string.h related functions: strcmp, strcpy, strlen, etc. • stdlib.h related functions: abs, fabs

  9. User-defined function • What do we need to define and make use of user-defined function? • Function prototype • Function definition • Function call

  10. Function prototype • Function prototype is a declaration; indicates the function exists • Should have function name, return type and parameter • Argument name is not compulsory in function header • Function prototype havethe following form: • <return_type> <function_name> (arg_type arg_name, ...); • float ohm_law (float V, float R); • float ohm_law (float, float); //this is also acceptable have semicolon

  11. Function definition • Function definition includes the body of a function • Function definition havethe following form: • <return_type> <function_name> (arg_type arg_name, ...) { … statements … } • float ohm_law (float V, float R) { float I; I = V/R; return (I); } • Notice that argument name is used in the function body • Unlike function prototype, argument name in function definition must be included in function header no semicolon function header

  12. Function call • Consists of a function name followed by argument expression list enclosed in parentheses • Function call havethe following form: • <function_name> (exp, exp ...) • exp is an expression– can be variable or constant • result = ohm_law (x,y);

  13. Example of function in program //This program calculates the value of current flow #include <stdio.h> float ohm_law (float V, float R); //function prototype int main() { float voltage, resistance, result; printf( “Enter voltage and resistance : “); scanf(“%f %f”, &voltage, &resistance); result = ohm_law(voltage, resistance); //function call printf(“Current is : %f”, result); return 0; } float ohm_law (float V, float R) //function definition { float I; I = V/R; return (I); } function header

  14. What about number, order and type of parameter? • Number, order and type of parameters in the argument list of a function call and function definition MUST match. • If function prototype and definition have three parameters then the function call must have three parameters. • If the types are int, float and double in the prototype, the types in the function call should be int, float and double, respectively.

  15. What about number, order and type of parameter?(e.g1) float ohm_law (float V, float R); //function prototype float ohm_law (float V, float R) //function definition ohm_law(voltage, resistance); //function call • Refer to program in slide 13 • Number, order and type parameter is met because :there are two parameters, the parameters are listed in order i.e respectively and first parameter is int and second parameter is int.

  16. What about number, order and type of parameter?(e.g2) *stop here • Note that there are two arguments for function prototype, function definition and function call; the first is int and the second is double.With these three we have met the number,order and type requirements.

  17. else { total_parallel = calculate_parallel (R1, R2); printf (“\n The total resistance is %f”, total_parallel ); } return 0; } float calculate_series (float x, float y) ??? { float total1 =0; total1 = x + y; return (total1); } float calculate_parallel (float a, float b) ??? { float total2 =0; total2 = 1/ (1/a + 1/b) ; return (total2); } Example: (assume only s and p can be entered by user) //This program calculates total resistance for series or parallel ciruit #include <stdio.h> float calculate_series (float, float); ??? float calculate_parallel (float, float); ??? int main () { char connection; float R1, R2, total_series = 0; float total_parallel =0; printf(“Enter R1 and R2 in ohm:”); scanf(“%f %f”, &R1, &R2); printf(“\n What is the circuit connection? Enter s for series and p for parallel: ”); scanf(“%c”, &connection); if (connection == ‘s’ || connection == ‘S’ ) { total_series = calculate_series (R1, R2); ??? printf (“\n The total resistance is %f”, total_series); }

  18. Functions that do not return a value – ‘void’ //This program calculates the value of current flow #include <stdio.h> void ohm_law(float, float); //function prototype void function1(); //function prototype int main() { float voltage, resistance; function1(); //function call printf( “Enter voltage and resistance : “); scanf(“%f %f”, &voltage, &resistance); ohm_law (voltage, resistance); //function call return 0; } void ohm_law (float V, float R) //function definition { float I; I = V/R; printf(“Current is : %f”, I); } void function1() //function definition { printf(“Welcome to this program\n”); }

  19. Example: Determine a colour of resistor band for an entered value #include <stdio.h> void colour_resistor (int); int main() { int colour; printf (“Enter value of colour band (0-9) >>”); scanf(“%d”, &colour); colour_resistor (colour); return 0; } void colour_resistor (int code) { int code; switch (code) { case 0: printf(“Resistor colour band is BLACK”); break; case 1: printf(“Resistor colour band is BROWN”); break; ....... …… case 9: printf(“Resistor colour band is WHITE”); break; } }

  20. Function call as logical expression //This program calculates the value of current flow #include <stdio.h> float ohm_law (float V, float R); //function prototype int main() { float voltage, resistance, result; printf( “Enter voltage and resistance : “); scanf(“%f %f”, &voltage, &resistance); if ( ohm_law(voltage, resistance) > 10 ); //function call {printf(“Increase resistance value”);} return 0; } float ohm_law (float V, float R) //function definition { float I; I = V/R; return (I); }

  21. Function call by printf statement //This program calculates the value of current flow #include <stdio.h> float ohm_law (float V, float R); //function prototype int main() { float voltage, resistance, result; printf( “Enter voltage and resistance : “); scanf(“%f %f”, &voltage, &resistance); printf(“Current is : %f”, ohm_law(voltage, resistance));//function call return 0; } float ohm_law (float V, float R) //function definition { float I; I = V/R; return (I); }

  22. Group Exercise: • Built function for each of the following, where user enter the value(s). • A program to: • tria_area – calculate triangle area • tria_peri – calculate triangle perimeter • A program to: • circ_perim – calculate circle perimeter • circ_area – calculate circle area • Print result at main function

  23. Recursive Functions • Recursion is a term describing functions which are called by themselves (functions that calls themselves) • Recursive function has two parts i.e. base case and non-base case • Recursion can be used to do something repeatedly (similar to loops). • For many problems, it is much easier to use recursion than loops to solve the problems. • Recursion is very useful in mathematical calculations and in sorting of lists

  24. Recursive Functions (cont.) • Example: factorial n! = n * ( n – 1 ) * ( n – 2 ) * … * 1 • Recursive relationship: • ( n! = n * ( n – 1 )! ) • 5! = 5 * 4! • 4! = 4 * 3!… • Base case (1! = 0! = 1)

  25. Recursive Functions • Application Example - Factorial 4 * 6 = 24 is returned Factorial(4) 3 * 2 = 6 is returned 4 * Factorial(3) 3 * Factorial(2) 2 * 1 = 2 is returned 2 * Factorial(1) Value 1 is returned 1

  26. Example (What is the ouput???) #include <stdio.h> int Factorial(int); int Factorial(int n) { if(n <= 1) return 1; else return ( n * Factorial(n-1)); • } • void main() • { • int a=4; • printf(“Factorial %d is %d“,a, Factorial(a)); • }

  27. Explanation Note: To see how the computation is done, trace factorial(4): factorial(4) = 4 * factorial(3) = 4 * (3 * factorial (2)) = 4* 3 * (2 * factorial(1)) = 4* 3 * (2 * (1 * factorial(0))) = 4 * 3 * (2 * (1 * 1))

  28. Example (Recursive Functions in Mathematic) • A fibonacci number is the sum of its two previous fibonacci numbers. • Given the equation below, • The sequence is: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181… • Example of a recursive formula: fib(n) = fib(n-1) + fib(n-2)

  29. f( 3 ) return f( 2 ) + f( 1 ) return f( 1 ) f( 0 ) return 1 + return 1 return 0 Recursive Functions (Example) • Diagram of Fibonacci function:

  30. Recursive Functions (Example) • Sample code for fibonacci function long fibonacci( long n ) { if ( n == 0 || n == 1 ) //base case return n; else return fibonacci( n - 1 ) + fibonacci( n – 2 ); } //non-base case • Try this if n =3?

  31. Self Exercise: Try this! (Ubuntu) • The code is correct, and you can put into your text editor (without the line numbers), save the document as a plain text file, let’s say “fib.c” and then open Terminal and type: gcc fib.c -o fib, and then you’ve compiled a program to be run in Terminal. fib.c was the source code, fib is the program name. You run it by typing ./fib 20 which outputs the twentieth fibonacci number. Be aware, at about ./fib 40 it begins taking several seconds. You can always abort it by pressing ctrl+c, if you chose a demanding number.

  32. Global Variable vs. Local Variable • A variable's scope is the range of the script where it is visible. • Scope refers to the region in which a declaration is active • File scope is also called global variable • declared at the top of a source file • declarations not placed in any functions • can be used by any statements that are being executed in the system • Function scope is also called local variable • declared in a block { … } • scope is within its block – lifetime while the block is executed

  33. Example 1 int i=4; /* Global declaration */ main() { i++; /* globalvariable */ /* what is the value of i here???? */ func(); /* what is the value of i here???? */ } void func(void) { int i=10; /* Iocal declaration */ i++; /* Iocalvariable */ /* what is the value of i here???? */ }

  34. Example 2 - what are the outputs??? int fuction1 (int a, int b, int c, int d) { int n = 400; printf(“\n n = %d m = %d a = %d”, n,m,a); m = 999; if (a>=1) { a + = b + m +n; printf(“\n m = %d a = %d”, m,a); return (a); } else { c + = d + m + n; return (c); } } #include <stdio.h> 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 m = %d n = %d e = %d”, m,n,e); i = function1(e,f,g,h); printf(“\n n = %d m = %d e = %d i = %d”, n,m,e,i); }

  35. Pass by Value • If a parameter is passed by value, then the value of the original data is copied into the function’s parameter (scope: local variable(s)) • In other words, it (i.e. local variable) has its own copy of the data • changes to copy do not change original data • During program execution, it (i.e. local variable) will manipulate the data stored in its own memory space

  36. #include <stdio.h> void fun1(int, int); //function prototype int main(void) { int a=5, b=10; printf("Before fun 1\n“); printf(" a = %d b = %d\n”, a, b); fun1(a, b); //function call printf("\nAfter fun 1\n“); printf(" a = %d b = %d\n”, a, b); return 0; } void fun1(int aa, int bb) //function definition { aa++; bb--; printf("\n\nInside fun 1\n)"; printf("aa = %d bb = %d\n”, aa, bb); } Output Before fun 1 a = 5 b = 10 Inside fun 1 aa = 6 bb = 9 After fun 1 a = 5 b = 10 Pass by Value (Example)

  37. Pass by Reference • A function’s parameter that receives the location (memory address) of the corresponding actual variables • When we attach * (star) after the arg_type in the parameter list of a function, then the variable following that arg_type is passed by reference • It stores the address of the actual variable, NOT the value • During program execution to manipulate the data, the address stored will direct control to the memory space of the actual variable • Syntax • In function protoype and function definition, put the * (star) after the data type • In function call, put the &(ampersand) before the argument name to be passed by reference

  38. #include <stdio.h> void fun1(int, int*); //function prototype int main(void) { int a=5, b=10; printf("Before fun 1\n“); printf(" a = %d b = %d“,a, b); fun1(a, &b); //function call printf(“\n\nAfter fun 1\n“); printf("a = %d b = %d\n“,a,b); return 0; } void fun1(int aa, int * bb) //function definition { aa++; *bb--; printf("\n\nInside fun 1\n“); printf("aa = %d bb = %d“,aa,bb); } Output Before fun 1 a=5 b = 10 Inside fun 1 aa = 6 bb = 9 After fun 1 a = 5 b = 9 Pass by Reference (Example)

  39. Which one to be used???? • It is the very first step in programming • Ask yourself–actual stuff or location??? • There are cases where you need to manipulate the value of an external variable from inside a function, thus we pass the values by reference • Pass by Reference are useful in two applications: • when you want to return more than one value from a function • when the value of the actual parameter needs to be changed Important Note!!! • pass addresses (references), NOT value/data • allows direct manipulation • changes will affect original data

  40. Comparison • Pass by Value • Pass by Reference

  41. Example: What are the outputs??? #include <stdio.h> void functionA(void); //function prototypes int functionB(int); void functionC(int *, int *); int globalA= 10; //global variables int main() { int mainC = 0, mainD = 0; functionA(); //function call printf("localB = %d\n",functionB(5)); //function call functionC(&mainC,&mainD); //function call printf("mainC = %d, mainD = %d\n", mainC,mainD); return 0; } void functionA(void) { int localA = 2; printf("localA = %d\n", localA); printf("globalA = %d\n", globalA); } int functionB(int localB) //pass by value { return localB; } void functionC(int *localC, int *localD) //pass by reference { *localC = 8; *localD = 9; }

  42. Sample application • Write a C program that calculates and prints the body mass index (bmi) of a person. • Your program should have 3 functions: • read– read height and weight of a person • calc_bmi– calculate bmi • print - print bmi

  43. #include <stdio.h> void read_bmi (float*,float*); float calc_bmi (float, float); void print (float); int main(void) { float height, weight, bmi; read_bmi (&height, &weight); bmi = calc_bmi (height, weight); print (bmi); return 0; } void read_bmi (float *h, float *w) { printf("Enter height and weight : "); scanf("%f %f", h, w); //notice no & is used } float calc_bmi (float h, float w) { return (w / (h*h) ); } void print (float result) { printf("\nYour bmi is :%.2f\n",result); } Sample application Functions that “return” more than one value i.e. arguments are pass by reference Output Enter height and weight : 1.63 48 Your bmi is: 18.07

  44. PKKKK Test Question (1) The kinematics equations (1) and (2) below describe an object motions based on their distance traveled (d), initial velocity (vi), final velocity (v), acceleration (a) and time taken (t). v2 = vi2 + 2ad (1) v = vi + at (2) Write a C program to read the value of v, vi and d from user and perform the calculation to determine a and t and print all the values. • Your program should have 2 functions: • read – read inputs • calc_at–determine and calculate value of a and t

  45. #include <stdio.h> void read(float *, float *, float *); void calc_at(float, float, float); int main() { float velocity, init_velocity, distance; read (&velocity, &init_velocity,&distance); calc_at(velocity, init_velocity, distance); return 0; } Solution void read(float *v, float *vi, float*d ) { printf("Enter values for v, vi and d : "); scanf("%f %f %f", v, vi, d); } void calc_at(float v, float vi, float d) { float a, t; a=( (v*v) – (vi * vi))/(2 *d); t = (v-vi)/a; printf (”\n a is %f”, a); printf (”\n t is %f”, t); }

  46. PKKKK Test Question (2) Write down the output for the following program: [5 marks] #include <stdio.h> void swapnum(int *i, int *j); void swapnum(int *i, int *j) { int temp = i; i = j; j = temp; } int main(void) { int a = 10; int b = 20; swapnum(&a, &b); printf("A is %d and B is %d\n", a, b); return 0; }

  47. Sample application • Write a C program that reads character and calculates numbers of vowel and consonant • Your program should have 3 functions: • read – read character • find_count_vc–determine and calculate number of vowel or consonant • print -print number of vowel or consonant

  48. #include <stdio.h> char read(); void find_count_vc(char, int*, int*); void print(int,int); int main() { char ch, choice; int count_v=0,count_c=0; do { ch = read(); find_count_vc(ch, &count_v, &count_c); printf("Do you want to continue?"); scanf("%c", &choice); }while((choice == 'y') ||(choice =='Y')); print(count_v,count_c); return 0; } char read() { char ch1; printf("Enter character : "); scanf("%c", &ch1); return(ch1); } void find_count_vc(char ch1, int *vowel, int *consonant) { switch(ch1) { case 'A': case 'a': case 'E': case 'e': case 'I': case 'i': case 'O': case 'o': case 'U': case 'u': *vowel = *vowel +1;break; default: *consonant = *consonant + 1; } } void print(int vowel, int consonant) { printf("Number of vowel : %d\n", vowel); printf("Number of consonant : %d\n", consonant); } Sample application Enter character : f Do you want to continue?y Enter character : I Do you want to continue?y Enter character : k Do you want to continue?n Number of vowel : 1 Number of consonant : 2 Functions that “return” more than one value i.e. arguments are passed by ref

  49. End Lecture – Functions Q & A!

More Related