Function lecture

812 views
735 views

Published on

Function is an important chapter in programming language C.
this lecture slides are prepared considering BTech 1st year student in India.

Published in: Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
812
On SlideShare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
48
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Function lecture

  1. 1. A Lecture on Function in CPrepared by:AJAY KUMARAssistant ProfessorDepartment of CSEDIT University, Dehradun
  2. 2. Introduction to Function in C• Rely on person for so many other thingsEg. call a mechanic to fix up your bike hire a gardener to mow your lawn rely on a store to supply you groceries every month• Similarly a computer program cannot handle all the tasks by itself.• So it requests other program —called ‘functions’ in C—to get its tasks done.visit us: http://sites.google.com/site/kumarajay7th/ 2
  3. 3. Modular Programming (Top-Down Programming)• Large program is broken into segments i.e.number of smaller and simpler tasks.• All individual segment is known as “module”.Eg. In a mobile phone, contact list SMS calculator Module games so on…visit us:http://sites.google.com/site/kumarajay7th/ 3
  4. 4. Advantage of Modular Programming• Codes and variables are isolated from other program• Easy to debug or trace the errors• Reuse the same code in other program also• Less effort to write a new code for similar taskeg. printf(), scanf(), clrscr(),sqrt()visit us: http://sites.google.com/site/kumarajay7th/ 4
  5. 5. Function• A function is a self-contained block of statements that perform a coherent task of some kind.• A function that calls or activates the function and the function itself. F SYSTEM-DEFINED FUNCTION U Or PRE-DEFINED function N Or Library function C Or Built-in Function T I O User-Defined Function N 5visit us: http://sites.google.com/site/kumarajay7th/
  6. 6. Basic structure of functionReturn_type function_name (arguments_list){ set of statements (or function body)}visit us: http://sites.google.com/site/kumarajay7th/ 6
  7. 7. Function (contd…)• Built-in FunctionEg. Sqrt(),pow(),printf(),scanf()• User-defined Function’s components – Return type – Function name – Function argument list – Function’s body= set of statementsvisit us:http://sites.google.com/site/kumarajay7th/ 7
  8. 8. Function categories on the basis of argument_list and return_type• Function with no arguments and no return values• Function with arguments and no return values• Function with arguments and return values• Function with no arguments and return valuesvisit us:http://sites.google.com/site/kumarajay7th/ 8
  9. 9. First Program of Function #include<stdio.h> #include<conio.h> void main() Output: { clrscr();1 printf(“n hello ”); Hello message(); printf(“n everyone”); Good morning 3 getch(); everyone } // function start message() { 2 printf(“n good morning”); } visit us: http://sites.google.com/site/kumarajay7th/ 9
  10. 10. First program of Function#include<stdio.h> Header File#include<conio.h>void main() Main function{ (Calling function)clrscr();printf(“n hello ”);message(); body of statement in main functionprintf(“n everyone”);getch();}// function start Commentsmessage() User-defined function name{ (Called function)printf(“n good morning”); Body of statement in user-defined functi} visit us: http://sites.google.com/site/kumarajay7th/ 10
  11. 11. Program examplevoid main( ){printf ( "ni am in main function" ) ; Output:italy( ) ;printf(“n i am in middle of main”);brazil( ) ; ?printf(“n i am back to main”);getch(); Output:} I am in main functionitaly() Hi how are you?{ I am in middle of mainprintf(“n Hi how are you?”); Hmmm, not bad} I am back to mainbrazil(){printf(“n Hmmm, not bad!”);} visit us: http://sites.google.com/site/kumarajay7th/ 11
  12. 12. Why use function?• Writing functions avoids rewriting the same code over and over.• Separating the code into modular functions makes the program easier to design and understand.visit us: http://sites.google.com/site/kumarajay7th/ 12
  13. 13. Function categories on the basis of argument_list and return_type• Function with no arguments and no return values• Function with arguments and no return values• Function with arguments and return values• Function with no arguments and return valuesvisit us: http://sites.google.com/site/kumarajay7th/ 13
  14. 14. Function with no arguments and no return values#include<stdio.h>#include<conio.h> Function prototype declarationvoid my_sms(void);void main() output:{ printf(“n send me a message”); my_sms(); send me a message my_sms(); plz rd my msg} plz rd my msgvoid my_sms(){print(“n plz rd my msg.”);} visit us: http://sites.google.com/site/kumarajay7th/ 14
  15. 15. Function with arguments and no return values#include<stdio.h>void factorial(int);void main(){ int n;printf(“n enter a no.”);scanf(“%d”, &n); Output:factorial(n);getch();} Enter a no. 5void factorial(int m) Factorial of 5 is 120{int i,f=1;for(i=1;i<=m;i++)f=f*i;printf(“n factorial of %d is %d”, m,f);} visit us: http://sites.google.com/site/kumarajay7th/ 15
  16. 16. Function with arguments and return values #include<stdio.h>#include<stdio.h> float add (int,int); ?int compute(int,int); void main()void main() {{int n1=100,n2=500,ans;ans=compute(n1,n2); ? float n1,n2,ans; printf(“n enter 2 no.”); scanf(“%f%f”,&n1,&n2);printf(“n largest no=%d”,ans); ans=add(n1,n2);getch(); printf(“n sum=%f”,ans);} getch(); }int compute(int x,int y) float add(int a,int b){ {if(x>y) float result;return x; result=a+b;else return result;return y; } 16 visit us: http://sites.google.com/site/kumarajay7th/
  17. 17. Function with No arguments and return values#include<stdio.h> int p()#include<conio.h> {int p(); int i,power=1,n;void main() printf("n enter value for power:");{ scanf("%d",&n); int my_p; clrscr(); for(i=1;i<=n;i++) my_p=p(); power=power*n; printf("n power = %d", my_p); getch(); return power;} } Output: enter value for power: 5 55= 5 x 5 x 5 x 5 x 5=3125 Power= 3125visit us: http://sites.google.com/site/kumarajay7th/ 17
  18. 18. Excercise Exercise: void main(){ void main() int i = 10, j = 20 ; { printf ( "%d %d %d ", i, j ) ; int a = 1 ; printf ( "%d", i, j ) ; printf ( "%d %d %d", a,++a,a++ ) ; } } Output; 10 20 860 Output: 10 331 Garbage valuevisit us: http://sites.google.com/site/kumarajay7th/ 18
  19. 19. assignment• WAP to find the factorial of a number using function with arguments and return value• Wap to find the cube of a number using function with argument but no return value• Write a c function which returns the biggest of 3 numbers.• Do the exercise from Let-Us-Cvisit us: http://sites.google.com/site/kumarajay7th/ 19
  20. 20. Function PrototypeDeclaring a function is function prototype whichprovides the compiler with a description that will bedefined at a later point in the program.Syntax:Return_type function_name(arg-type-1,arg-type-2,……..arg-type-n);Example:int my_square(int);double amount(int,float,int);void useless_msg(char[],int);visit us: http://sites.google.com/site/kumarajay7th/ 20
  21. 21. Function definition • An actual function is a snippet code that gets executed. • First line of function definition (known as function header) should be identical to function prototype with no semicolon. • Example: int my_square(int x) { Snippet long int my_sq; code my_sq=x*x; return my_sq;visit us: http://sites.google.com/site/kumarajay7th/ } 21
  22. 22. Actual and Formal Parameter #include<stdio.h> int compute_sum(int,int); void main() Actual Arguments { Variable used in (or Actual Parameter) int sum,n1=10,n2=30; Calling function sum=compute_sum(n1,n2); printf(“total =%d”,sum); getch(); } int compute_sum(int x, int y) { return (x+y); Variable used in Formal Parameter } Called functionvisit us: http://sites.google.com/site/kumarajay7th/ 22
  23. 23. Actual & Formal Parameter example#include<stdio.h> #include<stdio.h> Output Outputvoid plz_do_it(int); square (float); Enter a number: 2 Enter a number: 2void main( ) Output: void main() 4.00000 4.00000 Enter a number: 2.5 Enter a number: 2.5{ 60 { 6.000000 6.000000int a = 30 ; 30 int a; printf(“n enter a number”); wrongplz_do_it ( a ) ; scanf(“%f”,&a);printf ( "n%d", a ) ; printf(“%f”,square(a));} }void plz_do_it ( int b ) square(float x){ {b = 60 ; return (x*x);printf ( "n%d", b ) ; }} visit us: http://sites.google.com/site/kumarajay7th/ 23
  24. 24. Actual & Formal Parameter example#include<stdio.h> #include<stdio.h> wrong Outputvoid plz_do_it(int); float square (float); Enter a number: 2void main( ) Output: void main() 4.00000 { Enter a number: 2.5{ 60 6.000000int a = 30 ; 30 int a; printf(“n enter a number”);plz_do_it ( a ) ; scanf(“%f”,&a);printf ( "n%d", a ) ; printf(“%f”,square(a)); correct} } Outputvoid plz_do_it ( int b ) float square(float x) Enter a number: 2{ { 4.00000 Enter a number: 2.5b = 60 ; return (x*x); 6.250000printf ( "n%d", b ) ; } Enter a number:1.5} 2.250000 24 visit us: http://sites.google.com/site/kumarajay7th/
  25. 25. Scope Rules• The scope of a variable is in the program or function in which it is declared.• A global variable is visible to all contained functions including the function in which the variable is declared.• An entity* declared in the scope of another entity is always a different entity even if their names are identical. entity*= variable, function, parametervisit us: http://sites.google.com/site/kumarajay7th/ 25
  26. 26. Scope Rule (contd…) 1. The scope of a variable is in the program or function in which it is declared.#include<stdio.h> void add(int x1,int x2)void add(int,int); { printf(“n sum=%d”,x1+x2);void mul(int,int); }void main() void mul(int y1,int y2){ {int a=20,b=10; printf(“n multiplication=%d”,y1*y2);add(a,b); }mul(a,b); Scope of variable a,b is within the main() only.} Scope of variable x1,x2 is within the add() only.visitus:http://sites.google.com/site/kumarajay7th/ Scope of variable y1,y2 is within the mul() only. 26
  27. 27. Scope Rule (contd…) 2. A global variable is visible to all contained functions including the function in which the variable is declared.#include<stdio.h> Global variableint add_me(); A variable declared outside of a function.int n1,n2; They are known or accessed by any functionvoid main() { comprising the program.int my_sum;my_sum=add_me();printf(“n sum=%d”,my_sum);} /* end of main*/ Local Variableint add_me(){ A variable declared inside of a function. They areint result; unknown to other function. i.e. scope is only withinResult=n1+n2; the function in which They are declared. Variable arereturn result; Not accessed outside of function. visit us: http://sites.google.com/site/kumarajay7th/ 27}
  28. 28. Scope Rules (contd…)• An entity* declared in the scope of another entity is always a different entity even if their names are identical. entity*= variable, function, parameter Example; ??????visit us: http://sites.google.com/site/kumarajay7th/ 28
  29. 29. Parameter passing method on the basis of argument (or parameter) Parameter passing method Pass by Value Pass by Reference Or Call by value Or Call by ReferenceWhen the values of arguments are passed Actual values are not passed, insteadFrom the calling function to the called their addresses are passed. There is nofunction, The values are copied into called copying of values since their memoryfunction. locations are referenced.If any changes made to the value in calling If any changes is made to value infunction, There is no change in the original called function, The original value getsvalues within the calling function. changed within the calling function. 29 visit us :http://sites.google.com/site/kumarajay7th/
  30. 30. Call by values//swaping the value by callByValue //no change in calling function#include<stdio.h>void call_by_value(int,int); #include<stdio.h>void main( ) void no_change_value(int);{ void main( ) Output:int a = 10, b = 20 ; { B=60call_by_value ( a, b ) ; int a = 30 ; A=30printf ( "na = %d t b = %d", a, b ) ; no_change_value ( a ) ;} printf ( "na=%d", a ) ;void call_by_value ( int x, int y ) }{ void no_change_value ( int b )int t ; Output: {t=x; x = 20 y = 10 b = 60 ;x=y; a = 10 b = 20 printf ( "nb= %d", b ) ;y=t; }printf ( "nx = %d t y = %d", x, y ) ; visit us: http://sites.google.com/site/kumarajay7th/ 30}
  31. 31. Pointer (know it before using call by reference) Let us take an example, int i=3; This declaration tells the C compiler to: (a) Reserve space in memory to hold the integer value. (b) Associate the name i with this memory location. (c) Store the value 3 at this location.Memory map i Location nameFor Value at locationi’s location 65524 Location number 31 visit us: http://sites.google.com/site/kumarajay7th/
  32. 32. Pointer (contd…) Memory map i Location name For Value at location i’s location 65524 Location number void main( ) %u=unsigned integer output: { Address of i = 65524 int i = 3 ; Value of i = 3 printf ( "nAddress of i = %u", &i ) ; printf ( "nValue of i = %d", i ) ; } First time used & in printf() indicatingvisit us: http://sites.google.com/site/kumarajay7th/ address of variable 32
  33. 33. Pointer (contd…) &(address operator) and *(indirection operator) main( )main( ) {{ int i = 3 ;int i = 3 ; printf ( "nAddress of i = %u", &i ) ;printf ( "nAddress of i = %u", &i ) ; printf ( "nValue of i = %d", i ) ;printf ( "nValue of i = %d", i ) ; printf ( "nValue of i = %d", *( &i ) ) ;} }output: output: * is known asAddress of i = 65524 Address of i = 65524 ‘indirectionValue of i = 3 Value of i = 3 Value of i = 3 operator’ or ‘value at address’visit us: http://sites.google.com/site/kumarajay7th/ 33
  34. 34. Pointer (contd…) Output:main( ) Address of i = 65524{ Address of i = 65524 Pointer variable (‘j’ in Address of j = 65522int i = 3 ; this case) contains Value of j = 65524int *j ; Value of i = 3 address of other variable (‘i’ in this case) Value of i = 3j = &i ; Value of i = 3printf ( "nAddress of i = %u", &i ) ;printf ( "nAddress of i = %u", j ) ;printf ( "nAddress of j = %u", &j ) ; i jprintf ( "nValue of j = %u", j ) ;printf ( "nValue of i = %d", i ) ; 3 65524printf ( "nValue of i = %d", *( &i ) ) ; 65524 65522printf ( "nValue of i = %d", *j ) ;} visit us: http://sites.google.com/site/kumarajay7th/ 34
  35. 35. Call by reference//swapping the value by reference void call_by_reference( int *x, int *y )#include<stdio.h> {void call_by_reference(int*, int*); int t ;void main( ) { t = *x ;int a = 10, b = 20 ; *x = *y ;printf(“n before swappingn”); *y = t ;printf(“n a=%d t b=%d”,a,b); }call_by_reference( &a, &b ) ;printf(“n after swappingn”); Output:printf ( "na = %d b = %d", a, b ) ; before swapping} a=10 b=20 after swappingvisit us: http://sites.google.com/site/kumarajay7th/ a=20 b=10 35
  36. 36. Call by value vs call by reference Call by value Call by reference It consumes more memory It consumes less memory space because formal space because irrespective parameter also occupies of data type of the actual memory space. arguments, each pointer occupies only 4 bytes It takes more time to It takes less time because execute because the values no values are copied. are copied.visit us: http://sites.google.com/site/kumarajay7th/ 36
  37. 37. Exercise• Write a C program using function to find the numbers between 1 to 1000 which follows the property that 12 possesses. i.e. (a) The number is 12 (b) Take it reverse (i.e.21) and square it (i.e. 441) (c) Now take the square of 12 (i.e. 144) (d) Compare the result of step (b) & step (c) (e) If they are reverse of each other then print 12.visit us: http://sites.google.com/site/kumarajay7th/ 37
  38. 38. Recursion(A recursive function) • A function is called ‘recursive’ if a statement within the body of a function calls the same function. • Sometimes called ‘circular definition’, recursion is thus the process of defining something in terms of itself. • A situation in which a function calls itself either directly or indirectly.visit us:http://sites.google.com/site/kumarajay7th/ 38
  39. 39. Recursion (contd…)e.g. Recursion can be used to calculate factorial of a number.X!= x* (x-1)* (x-2)*(x-3)*…*2*1 e.g.However x! may be calculated as find the factorial of 4 X!=x*(x-1)!And then (x-1)!= (x-1)*(x-2)! 4!=4*3*2*1 OrAnd then (x-2)!=(x-2)*(x-3)! 4!=4*3!----------------------------------------------And so on…… visit us: http://sites.google.com/site/kumarajay7th/ 39
  40. 40. Recursion example . Q find the factorial of a number using recursionmain( ) rec ( int x ){ {int a, fact ; int f ;printf ( "nEnter any number " ) ; if ( x == 1 ) return ( 1 ) ;scanf ( "%d", &a ) ; elsefact = rec ( a ) ; return (x * rec ( x - 1 )) ;printf ( "Factorial value = %d", fact ) ; }} visit us: http://sites.google.com/site/kumarajay7th/ 40
  41. 41. Recursion concept understandingreturn ( x * rec ( x - 1 )) ; Important line rec ( 5 ) returns ( 5 times rec ( 4 ), which returns ( 4 times rec ( 3 ), which returns ( 3 times rec ( 2 ), which returns ( 2 times rec ( 1 ), which returns ( 1 ) ) ) ) ) visit us: http://sites.google.com/site/kumarajay7th/ 41
  42. 42. Recursion flow example Starts herevisit us: http://sites.google.com/site/kumarajay7th/ 42
  43. 43. Assignment on recursion1. Find the factorial of a given number using recursion.2. Generate fibonacci series upto nth terms using recursion3. Define power function using recursion4. Find the greatest common divisor (GCD) of 2 no.5. Conversion from decimal to binary visit us: http://sites.google.com/site/kumarajay7th/ 43
  44. 44. Special assignment on function• Go through Let-Us-C of chapter function• Try to generate your own function, say myf()• Save a defined function myf() with new .cpp file name , say myf.cpp• Save a new header file with declaring myf() prototype, say myf.h• Add this header file myf.h to TurboC library• Include this header file in your new file and execute the statement, #include ”myf.h”1. do_it(). 2.print_me(). 3.add_me() 4.print_table() visit us: http://sites.google.com/site/kumarajay7th/ 44
  45. 45. Data Storage in C 1.Variable’s value stores at two location: • Memory and • CPU Register 2.Variable’s storage class tells us:  Where the value would be stored.  Default initial value  Scope of a variable  Life of a variablevisit us: http://sites.google.com/site/kumarajay7th/ 45
  46. 46. Type of Storage Class Data storage Automatic Register Static Externalvisit us: http://sites.google.com/site/kumarajay7th/ 46
  47. 47. Automatic Storage Class (keyword:auto)• Storage- Memory• Default Initial Value- garbage value• Scope- local to the block in which variable is defined• Life- within the block void main( ) { void main( ) auto int i = 1 ; { { Output: auto int i, j ; { 1 1 1 { printf ( "n%d %d", i, j ) ; printf ( "n%d ", i ) ; } } printf ( "%d ", i ) ; Output: Garbage value } 1211 221 printf ( "%d", i ) ; } visit us: http://sites.google.com/site/kumarajay7th/ 47 }
  48. 48. Automatic Storage class examplevoid main( ){auto int i = 1 ; Output: { auto int i = 2 ; { 3 auto int i = 3 ; 2 printf ( "n%d ", i ) ; } 1 printf ( “n%d ", i ) ; }printf ( “n%d", i ) ;} 48 visit us: http://sites.google.com/site/kumarajay7th/
  49. 49. Register storage class• Storage - CPU registers.• Default initial value - Garbage value.• Scope - Local to the block in which the variable is defined.• Life - remains within the block in which the variable is defined. void main( ) { Register variable is register int i ; used to use the for ( i = 1 ; i <= 10 ; i++ ) variable frequently. printf ( "n%d", i ) ; } visit us: http://sites.google.com/site/kumarajay7th/ 49
  50. 50. Static Storage class • Storage − Memory. • Default initial value − Zero. • Scope − Local to the block in which the variable is defined. • Life − Value of the variable persists between different function calls. void main( ) increment( ) Output: { { 1 increment( ) ; static int i = 1 ; 2 increment( ) ; printf ( "%dn", i ) ; increment( ) ; i=i+1; 3 Output: } } auto int i=1; 1 1 50visit us:http://sites.google.com/site/kumarajay7th/ 1
  51. 51. External Storage Class (keyword:extern)• Storage − Memory.• Default initial value − Zero.• Scope − Global.• Life − As long as the program’s execution doesn’t come to an end.int i ; increment() { Output:main( ) i=i+1;{ printf ( "non incrementing i = %d", i ) ; i=0printf ( "ni = %d", i ) ; } on incrementing i = decrement( ) 1increment( ) ; { on incrementing i =increment( ) ; i=i-1; 2decrement( ) ; printf ( "non decrementing i = %d", i ) ; on decrementing i =decrement( ) ; } 1} visit us: http://sites.google.com/site/kumarajay7th/ on decrementing i = 51
  52. 52. Extern Storage Class Example int x = 21 ; global void main( ) { Declaring a variable extern int y ; Requires no space Defining a printf ( "n%d %d", x, y ) ; variable space gets } reserved int y = 31 ; globalvisit us:http://sites.google.com/site/kumarajay7th/ 52
  53. 53. Extern storage class example (contd…)int x = 10 ; Global xmain( ){ Confused ?int x = 20 ; Local xprintf ( "n%d", x ) ;display( ) ;} Output: Preference is given 20 to local variabledisplay( ){ 10printf ( "n%d", x ) ;} us: http://sites.google.com/site/kumarajay7th/visit 53
  54. 54. Excercise • From Let-Us-Cvisit us:http://sites.google.com/site/kumarajay7th/ 54

×