Se ha denunciado esta presentación.
Se está descargando tu SlideShare. ×
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Próximo SlideShare
Structure In C
Structure In C
Cargando en…3
×

Eche un vistazo a continuación

1 de 42 Anuncio

Más Contenido Relacionado

Presentaciones para usted (20)

Similares a Fnctions part2 (20)

Anuncio

Más reciente (20)

Anuncio

Fnctions part2

  1. 1. @2020 Presented By Y. N. D. Aravind 1 Presented By Y. N. D. ARAVIND M.Tech, Dept of CSE Newton’s Group Of Institutions, Macherla 1
  2. 2. Session Objectives Parameter Passing Passing Arrays to Functions Recursive Functions Function Components @2020 Presented By Y. N. D. Aravind 2 2
  3. 3. A function is a block of code that performs a specific task. It has a name and it is reusable .It can be executed from as many different parts in a program as required, it can also return a value to calling program. All executable code resides within a function. It takes input, does something with it, then give the answer. A computer program cannot handle all the tasks by itself. It requests other program like entities called functions in C. We pass information to the function called arguments which specified when the function is called. A function either can return a value or returns nothing. Function is a subprogram that helps reduce coding. return_type function_name (argument list) { Set of statements – Block of code } @2020 Presented By Y. N. D. Aravind 3 3 Function in C
  4. 4. Basically there are two reasons because of which we use functions 1. Writing functions avoids rewriting the same code over and over. For example - if you have a section of code in a program which calculates the area of triangle. Again you want to calculate the area of different triangle then you would not want to write the same code again and again for triangle then you would prefer to jump a "section of code" which calculate the area of the triangle and then jump back to the place where you left off. That section of code is called ..........„ function'. 2. Using function it becomes easier to write a program and keep track of what they are doing. If the operation of a program can be divided into separate activities, and each activity placed in a different function, then each could be written and checked more or less independently. Separating the code into modular functions also makes the program easier to design and understand. @2020 Presented By Y. N. D. Aravind 4 4 Why use Function
  5. 5.  Once a function is defined and called, it takes some data from the calling function and returns a value to the called function.  When ever a function is called, control passes to the called function and working of the calling function is stopped.  When the execution of the called function is completed, a control returns back to the calling function and executes the next statement.  The values of actual arguments passed by the calling function are received by the formal arguments of the called function.  The number of actual and formal arguments should be the same. If the formal arguments are more than the actual arguments then the extra arguments appear as garbage.  The function operates on formal arguments and sends back the result to the calling function. @2020 Presented By Y. N. D. Aravind 5 5 How Function’s Work
  6. 6. Def:- The function which is referring another function is called “calling function”. Def:- The function which is referenced by another function is called “called function” @2020 Presented By Y. N. D. Aravind 6 Calling Function and Called Function Actual Arguments and Formal Arguments Def:- The arguments of calling functions are called “actual arguments”. Def:- The arguments of called function are “formal arguments”. Local Variables and Global Variables Local variables:- The local variables are defined within the body of the function or the block. Other function cannot access these variables. Global variables:- Global variables are defined outside the main() function. Multiple functions can use them.
  7. 7. @2020 Presented By Y. N. D. Aravind 7
  8. 8. C provides library functions for performing some operations. These functions are present in the c library and they are predefined. For example sqrt() is a mathematical library function which is used for finding the square root of any number .The function scanf and printf() are input and output library function similarly we have strcmp() and strlen() for string manipulations. To use a library function we have to include some header file using the preprocessor directive #include. For example to use input and output function like printf() and scanf() we have to include stdio.h, for math library function we have to include math.h for string library string.h should be included. @2020 Presented By Y. N. D. Aravind 8 8 Library Function’s in C
  9. 9. A user can create their own functions for performing any specific task of program are called user defined functions. To create and use these function we have to know these 3 elements. 1. Function Declaration 2. Function Definition 3. Function Call @2020 Presented By Y. N. D. Aravind 9 User defined Function’s in C
  10. 10. 1. Function Declaration The program or a function that calls a function is referred to as the calling program or calling function. The calling program should declare any function that is to be used later in the program this is known as the function declaration or function prototype. 2. Function Definition The function definition consists of the whole description and code of a function. It tells that what the function is doing and what are the input outputs for that. A function is called by simply writing the name of the function followed by the argument list inside the parenthesis. Function definitions have two parts: Function Header The first line of code is called Function Header. int sum( int x, int y) It has three parts (i). The name of the function i.e. sum (ii). The parameters of the function enclosed in parenthesis (iii). Return value type i.e. int Function Body Whatever is written with in { } is the body of the function. 3. Function Call In order to use the function we need to invoke it at a required place in the program. This is known as the function call. @2020 Presented By Y. N. D. Aravind 10 User defined Function’s in C
  11. 11. A function depending on whether arguments are present or not and whether a value is returned or not may belong to any one of the following categories: I. Functions with no arguments and no return values. II. Functions with arguments and no return values. III. Functions with arguments and return values. IV. Functions with no arguments and return values. @2020 Presented By Y. N. D. Aravind 11 Categories Of Function’s
  12. 12. There is no data communication between the calling portion of a program and a called function block. The function is invoked bya calling environment by not passing any formal arguments and the function also does not return back any value to the caller. No Input No Output No data communication between functions @2020 Presented By Y. N. D. Aravind 12 Function’s with no arguments and no return values function1() { --------------------- --------------------- --------------------- function2(); /* function call*/ --------------------- --------------------- } function2() { --------------------- --------------------- --------------------- --------------------- --------------------- }
  13. 13. #include<stdio.h> #include <conio.h> void maximum(); { int x,y,z,max; printf( “ Enter three Numbers n”); scanf(“%d%d%d”, &x,&y,&z); max = x; if(y > max) max = y; if(z > max) max = z; printf(“Maximum = %d n”,max); } void main() { clrscr(); maximum(); getch(); } @2020 Presented By Y. N. D. Aravind 13 Function’s with no arguments and no return values Input- Output Enter three Numbers 1 2 3 Maximum = 3
  14. 14. The second type of user defined function passes some formal arguments to a function but the function does not return back any value to the caller. It is an one – way data communication between the calling portion of a program and a called function block. Values of arguments No return values One – way data communication between functions @2020 Presented By Y. N. D. Aravind 14 Function’s with arguments and no return values function1() { --------------------- --------------------- --------------------- function2(x); /* function call*/ --------------------- --------------------- } function2(a) { --------------------- --------------------- --------------------- --------------------- --------------------- }
  15. 15. #include<stdio.h> #include <conio.h> void maximum(int, int, int); void main() { int x,y,z; clrscr(); printf( “ Enter three Numbers n”); scanf(“%d%d%d”, &x,&y,&z); maximum(x,y,z); getch(); } void maximum(int a, int b, int c) { int max; max = a; if(b > max) max = b; if(c > max) max = c; printf(“Maximum = %d n”,max); } @2020 Presented By Y. N. D. Aravind 15 Function’s with arguments and no return values Input- Output Enter three Numbers 1 2 3 Maximum = 3
  16. 16. The third type of user defined function passes some formal arguments to a function from a calling portion of the progra and the computed value, if anyy, is transferred back to the caller. Data are communicated between the calling portion of a program and a called function block. Values of arguments Function results Two – way data communication between functions @2020 Presented By Y. N. D. Aravind 16 Function’s with arguments and with return values function1() { --------------------- --------------------- --------------------- function2(x); /* function call*/ --------------------- --------------------- } function2(a) { --------------------- --------------------- --------------------- --------------------- --------------------- return(z); }
  17. 17. #include<stdio.h> #include <conio.h> int maximum(int x, int y, int z); void main() { int x,y,z,maxi; clrscr(); printf( “ Enter three Numbers n”); scanf(“%d%d%d”, &x,&y,&z); maxi = maximum(x,y,z); printf(“Maximum = %d n”,maxi); getch(); } int maximum(int x, int y, int z) { int max; max = x; if(y > max) max = y; if(z > max) max = z; return(max); } @2020 Presented By Y. N. D. Aravind 17 Function’s with arguments and with return values Input- Output Enter three Numbers 1 2 3 Maximum = 3
  18. 18. The fourth type of user defined function, the function is invoked by a calling environment by not passing any formal arguments to a function but the computed value, if any, is transferred back to the caller. Data are communicated between the calling portion of a program and a called function block in one way. No Input Function results One – way data communication between functions @2020 Presented By Y. N. D. Aravind 18 Function’s with no arguments and return values function1() { --------------------- --------------------- --------------------- function2(); /* function call*/ --------------------- --------------------- } function2() { --------------------- --------------------- --------------------- --------------------- --------------------- return(z); }
  19. 19. #include<stdio.h> #include <conio.h> int maximum(); void main() { int max; clrscr(); max = maximum(); printf(“Maximum = %d n”,max); getch(); } int maximum() { int x,y,z,max; printf( “ Enter three Numbers n”); scanf(“%d%d%d”, &x,&y,&z); max = x; if(y > max) max = y; if(z > max) max = z; return(max); } @2020 Presented By Y. N. D. Aravind 19 Function’s with no arguments and return values Input- Output Enter three Numbers 1 2 3 Maximum = 3
  20. 20. @2020 Presented By Y. N. D. Aravind 20 Presented By Y. N. D. ARAVIND M.Tech, Dept of CSE Newton’s Group Of Institutions, Macherla 20
  21. 21. Most programming languages have 2 strategies to pass parameters. They are i. Call by value ii. Call by address Pass by value (or) call by value :- In this method calling function sends a copy of actual values to called function, but the changes in called function does not reflect the original values of calling function. Pass by reference (or) call by address :- In this method calling function sends address of actual values as a parameter to called function, called function performs its task and sends the result back to calling function. Thus, the changes in called function reflect the original values of calling function. To return multiple values from called to calling function we use pointer variables. Calling function needs to pass ..„&‟ operator along with actual arguments and called function need to use „*‟ operator along with formal arguments. Changing data through an aaddress variable is known as indirect access and „*‟ is represented as indirection operator. @2020 Presented By Y. N. D. Aravind 21 Parameter Passing
  22. 22. Pass by value (or) call by value :- Function call by value is the default way of calling a function in C programming. Before we discuss function call by value, lets understand the terminologies that we will use while explaining this: Actual parameters: The parameters that appear in function calls. Formal parameters: The parameters that appear in function declarations. When we pass the actual parameters while calling a function then this is known as function call by value. In this case the values of actual parameters are copied to the formal parameters. Thus operations performed on the formal parameters don‟t reflect in the actual parameters. Call By Value: In this parameter passing method, values of actual parameters are copied to function‟s formal parameters and the two types of parameters are stored in different memory locations. So any changes made inside functions are not reflected in actual parameters of caller. @2020 Presented By Y. N. D. Aravind 22 Pass by Valur (or) Call By Value
  23. 23. Pass by reference (or) call by address :- Before we discuss function call by reference, lets understand the terminologies that we will use while explaining this: Actual parameters: The parameters that appear in function calls. Formal parameters: The parameters that appear in function declarations. When we call a function by passing the addresses of actual parameters then this way of calling the function is known as call by reference. In call by reference, the operation performed on formal parameters, affects the value of actual parameters because all the operations performed on the value stored in the address of actual parameters. It may sound confusing first but the following example would clear your doubts. Call by Reference: Both the actual and formal parameters refer to same locations, so any changes made inside the function are actually reflected in actual parameters of caller. Calling function needs to pass ..„&‟ operator along with actual arguments and called function need to use „*‟ operator along with formal arguments. Changing data through an aaddress variable is known as indirect access and „*‟ is represented as indirection operator. @2020 Presented By Y. N. D. Aravind 23 Pass by Reference (or) Call by address
  24. 24. @2020 Presented By Y. N. D. Aravind 24 Pass by value (or) call by value Pass by reference (or) call by address #include<stdio.h> void fun1(int, int); void main( ) { int a=10, b=15; Printf(“values of a and b before function call n”); printf(“a=%d,b=%d”, a,b); fun1(a,b); Printf(“values of a and b after function call n”); printf(“a=%d,b=%d”, a,b); } void fun1(int a, int b) { a=a+10; b= b+20; Printf(“values of a and b incalled function n”); printf(“a=%d,b=%d”, a,b); } #include<stdio.h> void fun1(int *, int *); void main( ) { int a=10, b=15; Printf(“values of a and b before function call n”); printf(“a=%d,b=%d”, a,b); fun1(&a,&b); Printf(“values of a and b after function call n”); printf(“a=%d,b=%d”, a,b); } void fun1(int *a, int *b) { *a= *a+10; *b= *b+20; Printf(“values of a and b incalled function n”); printf(“a=%d,b=%d”, a,b); } values of a and b before function call a=10 b=15 values of a and b incalled function a=20 b= 35 values of a and b after function call a=10 b=15 values of a and b before function call a=10 b=15 values of a and b incalled function a=2000 b= 3000 values of a and b after function call a=20 b=35
  25. 25. @2020 Presented By Y. N. D. Aravind 2000 a 2001 2002 : : 3000 b Main () fun1() 10 15 3500 a 3501 3502 : : 4000 b 10 15 20 35 Main () fun1() 2000 a 2001 2002 : : 3000 b 3500 a 3501 3502 : : 4000 b 10 15 2000 3000 20 35 25
  26. 26. @2020 Presented By Y. N. D. Aravind 26 Pass by value (or) call by value Pass by reference (or) call by address #include<stdio.h> void swap(int, int); void main( ) { int a=10, b=15; Printf(“values of a and b before function call n”); printf(“a=%d,b=%d”, a,b); swap(a,b); Printf(“values of a and b after function call n”); printf(“a=%d,b=%d”, a,b); } void swap(int a, int b) { int temp; temp =a; a=b; b= temp; Printf(“values of a and b incalled function n”); printf(“a=%d,b=%d”, a,b); } #include<stdio.h> void swap(int *, int *); void main( ) { int a=10, b=15; Printf(“values of a and b before function call n”); printf(“a=%d,b=%d”, a,b); swap(&a,&b); Printf(“values of a and b after function call n”); printf(“a=%d,b=%d”, a,b); } void swap(int *x, int *y) { int temp; temp = *x; *x=*y; *x= temp; Printf(“values of a and b incalled function n”); printf(“a=%d,b=%d”, *x,*y); } values of a and b before function call a=10 b=15 values of a and b incalled function a=15 b= 10 values of a and b after function call a=10 b=15 values of a and b before function call a=10 b=15 values of a and b incalled function x=15 y= 10 values of a and b after function call a=15 b=10
  27. 27. @2020 Presented By Y. N. D. Aravind 2000 a 2001 2002 : : 3000 b Main () fun1() 10 15 3500 a 3501 3502 temp : : 4000 b 10 15 15 10 Main () fun1() 2000 a 2001 2002 : : 3000 b 3500 a 3501 3502 temp : : 4000 b 10 15 2000 3000 15 10 10 10 27
  28. 28. @2020 Presented By Y. N. D. Aravind 28 STORAGE CLASSES Variables in C differ in behavior. The behavior depends on the storage class a variable may assume. From C compiler‟s point of view, a variable name identifies some physical location within the computer where the string of bits representing the variable‟s value is stored. There are four storage classes in C: 1. Automatic storage class 2. External storage class 3. Static storage class 4. Register storage class Syntax:- storage_class var_data_type var_name;
  29. 29. @2020 Presented By Y. N. D. Aravind 29 1. Automatic storage class  This is the default storage class for all the variables declared inside a function or a block.  Hence, the keyword auto is rarely used while writing programs in C language.  Auto variables can be only accessed within the block/function they have been declared and not outside them (which defines their scope).  Of course, these can be accessed within nested blocks within the parent block/function in which the auto variable was declared.  They are assigned a garbage value by default whenever they are declared.
  30. 30. @2020 Presented By Y. N. D. Aravind 30 2. Extern storage class  Extern storage class simply tells us that the variable is defined elsewhere and not within the same block where it is used.  Basically, the value is assigned to it in a different block and this can be overwritten/changed in a different block as well.  So an extern variable is nothing but a global variable initialized with a legal value where it is declared in order to be used elsewhere.  It can be accessed within any function/block.  Also, a normal global variable can be made extern as well by placing the „extern‟ keyword before its declaration/definition in any function/block.  This basically signifies that we are not initializing a new variable but instead we are using/accessing the global variable only.  The main purpose of using extern variables is that they can be accessed between two different files which are part of a large program.
  31. 31. @2020 Presented By Y. N. D. Aravind 31 3. Static storage class  This storage class is used to declare static variables which are popularly used while writing programs in C language.  Static variables have a property of preserving their value even after they are out of their scope! Hence, static variables preserve the value of their last use in their scope. So we can say that they are initialized only once and exist till the termination of the program.  Thus, no new memory is allocated because they are not re-declared.  Their scope is local to the function to which they were defined.  Global static variables can be accessed anywhere in the program. By default, they are assigned the value 0 by the compiler.
  32. 32. @2020 Presented By Y. N. D. Aravind 32 4. Register storage class  This storage class declares register variables which have the same functionality as that of the auto variables. The only difference is that the compiler tries to store these variables in the register of the microprocessor if a free register is available. This makes the use of register variables to be much faster than that of the variables stored in the memory during the runtime of the program. If a free register is not available, these are then stored in the memory only. Usually few variables which are to be accessed very frequently in a program are declared with the register keyword which improves the running time of the program. An important and interesting point to be noted here is that we cannot obtain the address of a register variable using pointers.
  33. 33. @2020 Presented By Y. N. D. Aravind 33 STORAGE CLASS STORAGE SPECIFIER STORAGE INITIAL VALUE KEYWORD SCOPE LIFETIME AUTO Main Memory Garbage value auto With in block End of Block EXTERN Main Memory Zero extern Entire Program Till End of Program STATIC Main Memory Zero static With in block Till End of Program REGISTAR Registar Garbage value register With in block End of Block
  34. 34. @2020 Presented By Y. N. D. Aravind 34 Recursion Recursion is a process by which a function calls itself repeatedly, until some specified condition has been satisfied. When a function calls itself, a new set of local variables and parameters are allocated storage on the stack, and the function code is executed from the top with these new variables. A recursive call does not make a new copy of the function. Only the values being operated upon are new. As each recursive call returns, the old local variables and parameters are removed from the stack, and execution resumes immediately after the recursive call inside the function. The main advantage of recursive functions is that we can use them to create clearer and simpler versions of several programs.
  35. 35. @2020 Presented By Y. N. D. Aravind 35 Recursion Recursion is a process by which a function calls itself repeatedly, until some specified condition has been satisfied. The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called as recursive function. Using recursive algorithm, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc. int main() { rec(); ... return 0; } void rec() { statement 1; ... rec(); } In the beginning main() function called rec(), then inside rec() function, it called itself again. As you can guess this process will keep repeating indefinitely. So, in a recursive function, there must be a terminating condition to stop the recursion. This condition is known as the base condition.
  36. 36. @2020 Presented By Y. N. D. Aravind 36 Recursion Recursion is a process by which a function calls itself repeatedly, until some specified condition has been satisfied. void recurse() { ... .. ... recurse(); ... .. ... } int main() { ... .. ... recurse(); ... .. ... }
  37. 37. @2020 Presented By Y. N. D. Aravind 37 Recursion The recursion continues until some condition is met to prevent it. To prevent infinite recursion, if...else statement (or similar approach) can be used where one branch makes the recursive call, and other doesn't. #include <stdio.h> int sum(int n); void main() { int number, result; printf("Enter a positive integer: "); scanf("%d", &number); result = sum(number); printf("sum = %d", result); } int sum(int n) { if (n != 0) // sum() function calls itself return n + sum(n-1); else return n; } OUTPUT Enter a positive integer:3 sum = 6
  38. 38. @2020 Presented By Y. N. D. Aravind 38 Find the factorial of a number using Recursion #include <stdio.h> unsigned long long int factorial(unsigned int i) { if(i <= 1) return 1; else return i * factorial(i - 1); } int main() { int i = 12; printf("Factorial of %d is %dn", i, factorial(i)); return 0; } Output When the above code is compiled and executed, it produces the following result − Factorial of 12 is 479001600
  39. 39. @2020 Presented By Y. N. D. Aravind 39 Fibonacci Series : The following example generates the Fibonacci series for a given number using a recursive function − #include <stdio.h> int fibonacci(int i) { if(i == 0) return 0; else if(i == 1) return 1; else return fibonacci(i-1) + fibonacci(i-2); } int main() { int i; for (i = 0; i < 10; i++) printf("%dt", fibonacci(i)); return 0; } OUTPUT 0 1 1 2 3 5 8 13 21 34
  40. 40. @2020 Presented By Y. N. D. Aravind 40 Passing Arrays as Function Arguments in C If you want to pass a single-dimension array as an argument in a function, you would have to declare a formal parameter in one of following three ways and all three declaration methods produce similar results because each tells the compiler that an integer pointer is going to be received. Similarly, you can pass multi-dimensional arrays as formal parameters. Way-1 : Formal parameters as a pointer void myFunction(int *param) { . . . } Way-2: Formal parameters as a sized array void myFunction(int param[10]) { . . . } Way-3 : Formal parameters as an unsized array void myFunction(int param[]) { . . . }
  41. 41. @2020 Presented By Y. N. D. Aravind 41 Now, consider the following function, which takes an array as an argument along with another argument and based on the passed arguments, it returns the average of the numbers passed through the array as follows − #include <stdio.h> double getAverage(int arr[], int size); /* function declaration */ int main () { int balance[5] = {1000, 2, 3, 17, 50}; /* an int array with 5 elements */ double avg; avg = getAverage( balance, 5 ) ; /* pass pointer to the array as an argument */ printf( "Average value is: %f ", avg ); /* output the returned value */ return 0; } double getAverage(int arr[], int size) { int i; double avg; double sum = 0; for (i = 0; i < size; ++i) sum += arr[i]; avg = sum / size; return avg; } When the above code is compiled together and executed, it produces the following result − Average value is: 214.400000
  42. 42. Thank You @2020 Presented By Y. N. D. Aravind Presented By Y. N. D. ARAVIND M.Tech, Dept of CSE Newton’s Group Of Institutions, Macherla 42

×