MODULE 3: FUNCTIONS CO3: Decompose a problem into functions and synthesize a complete program.
TOPICS TO BE COVERED Introduction to functions Function prototype/declaration Function definition Accessing a function Parameter passing Recursion
INTRODUCTION A function is a group of statements that together perform a task. Every C program has at least one function, which is main() You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division is such that each function performs a specific task. A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function. A function is a block of code that performs a specific task. Suppose, you need to create a program to draw a circle and color it. You can create two functions to solve this problem:  Create draw circle function  create a color function Dividing a complex problem into smaller chunks makes our program easy to understand and reuse.
INTRODUCTION Types of function There are two types of function in C programming: Standard library functions User-defined functions
INTRODUCTION Standard library functions The standard library functions are built-in functions in C programming. These functions are defined in header files. For example, •printf() •It is a standard library function to send formatted output to the screen (display output on the screen). •This function is defined in the stdio.h header file. •Hence, to use the printf() function, we need to include the stdio.h header file using #include <stdio.h>. • sqrt() •This function calculates the square root of a number. The function is defined in the math.h header file.
INTRODUCTION Library functions are those functions which are already defined in C library such as strcat(), printf(), scanf() etc. You just need to include appropriate header files to use these functions. The prototype and data definitions of these functions are present in their respective header files. To use these functions we need to include the header file in our program. For example, If you want to use the printf() function, the header file <stdio.h> should be included. If you try to use printf() without including the stdio.h header file, you will get an error
INTRODUCTION User-defined function User-defined functions are those functions which are defined by the user. These functions are made for code reusability and for saving time and space. You can also create functions as per your need. Such functions created by the user are known as user-defined functions. How user-defined function works? #include <stdio.h> void functionName() { ... .. ... ... .. ... } int main() { ... .. ... ... .. ... functionName(); ... .. ... ... .. ... }
INTRODUCTION The execution of a C program begins from the main() function. When the compiler encounters functionName();, control of the program jumps to void functionName() And, the compiler starts executing the codes inside functionName(). The control of the program jumps back to the main() function once code inside the function definition is executed .
INTRODUCTION Advantages of user-defined function The program will be easier to understand, maintain (add features later on) ,change and debug. Reusable codes that can be used in other programs A large program can be divided into smaller modules. Hence, a large project can be divided among many programmers.
FUNCTION DECLARATION Function Declaration: Syntax of function declaration: return_type function_name (data_type arg1, data_type arg2); int add(int x, int y); //function declaration In Function Declaration, we specify the name of the function, the number of input parameter, their data types & the return type of the function. Function declaration tells compiler about the list of arguments the function is expecting with their data types & the return type of the function. In function declaration, specifying the names of the parameter is optional, but specifying their data types is mandatory.
FUNCTION DEFINITION Function Definition
FUNCTION DEFINITION int add(int, int); //function declaration return_type function_name(parameters) { Function body } a function definition consists of two parts i.e. function header & function body
FUNCTION DEFINITION Function Header: function header is same as function declaration without the semicolon. Function header contains function name, parameter & return type.  Return Type: Return type is the data type of the value which will be returned by the function. The function may or may not return a value. If it does then the data type of the retuning value should be specified, otherwise the return type needs to be void.  Function Name: This is the name of the function using which we can call the function when & where needed.  Parameters: The parameters are the input values which will be passed to the function. It tells about the data types of the arguments, their order and the number of arguments that will be passed to the function. The parameters are optional. You can also have functions without parameters.
FUNCTION DEFINITION Function Body: The function body is the set of statement which performs a specific task. It defines what the function does. int add(int x, int y) { int sum = x+y; return(sum); } It is recommended to declare a function before we define & use it. In C, we can declare & define the function at the same place.
FUNCTION ARGUMENTS There are two types of parameter: Actual Parameter: Those parameters which are passed to functions while calling them is are known as actual parameter. For example, 23 & 31 in the above example are the actual parameters. Formal Parameter: Those parameters which are received by the functions are known as formal parameters. For example, x & y in the above example are the formal parameters.
TYPES OF USER-DEFINED FUNCTIONS 1. No arguments passed and no return value 2. No arguments passed but a return value 3. Argument passed but no return value 4. Argument passed and a return value
TYPES OF USER-DEFINED FUNCTIONS 1. No arguments passed and no return value Function with no return no argument, neither returns a value nor accepts any argument. This type of function does not communicate with the caller function. It works as an independent working block. Use this type of function when you have some task to do independent of the caller function. You must add void as function return type for this type of function.
TYPES OF USER-DEFINED FUNCTIONS 1. No arguments passed and no return value Syntax to define function with no return no argument void function_name() { // Function body }
TYPES OF USER-DEFINED FUNCTIONS 1. No arguments passed and no return value #include <stdio.h> void add(); void add() { int x = 20; int y = 30; int sum = x+y; printf("sum %d", sum); } int main() { add(); return 0; }
TYPES OF USER-DEFINED FUNCTIONS 2. No arguments passed but a return value Function with return but no arguments, returns a value but does not accept any argument. This type of function communicates with the caller function by returning value back to the caller. Syntax to define function with return but no arguments return_type function_name() { // Function body return some_value; } Where return_type and some_value must be declared with same type.
TYPES OF USER-DEFINED FUNCTIONS 2. No arguments passed but a return value #include <stdio.h> int add(); int add() { int x = 20; int y = 30; int sum = x+y; return(sum); } int main() { int sum; sum = add(); printf("sum %d", sum); return 0; }
TYPES OF USER-DEFINED FUNCTIONS 3. Argument passed but no return value Function with no return but with arguments, does not return a value but accepts arguments as input. For this type of function you must define function return type as void. Syntax to define function with no return but with arguments void function_name(type arg1, type arg2, ...) { // Function body } Where type is a valid C data type and argN is a valid C identifier.
TYPES OF USER-DEFINED FUNCTIONS 3. Argument passed but no return value #include <stdio.h> void add(int, int); void add(int x, int y) { int sum = x+y; return(sum); } int main() { add(23, 31); return 0; }
TYPES OF USER-DEFINED FUNCTIONS 4. Argument passed and a return value Function with return and arguments, returns a value and may accept arguments. Since the function accepts input and returns a result to the caller, hence this type of functions are dependent on each other. Syntax to define function with return and arguments return_type function_name(type arg1, type arg2, ...) { // Function body return some_variable; }
TYPES OF USER-DEFINED FUNCTIONS 4. Argument passed and a return value #include <stdio.h> int add(int, int); int add(int x, int y) { int sum = x+y; return(sum); } int main() { int sum = add(23, 31); printf("%d", sum); return 0; }
PARAMETER PASSING Function arguments are the inputs passed to a function. A function must declare variables to accept passed arguments. A variable that accepts function argument is known as function parameter. A function argument is commonly referred as actual parameter and function parameter is referred as formal parameter.
PARAMETER PASSING In C programming you can pass value to a function in two ways. 1. Call by value 2. Call by reference These two ways are generally differentiated by the type of values passed to them as parameters. The parameters passed to function are called actual parameters whereas the parameters received by function are called formal parameters.
PARAMETER PASSING
PARAMETER PASSING
PARAMETER PASSING – CALL BY VALUE Call by value is the default mechanism to pass arguments to a function. In Call by value, during function call actual parameter value is copied and passed to formal parameter. Changes made to the formal parameters does not affect the actual parameter. 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 the caller.
PARAMETER PASSING – CALL BY VALUE #include<stdio.h> void swap(int a, int b) { int temp; temp=a; a=b; b=temp; } void main() { int a=100, b=200; swap(a, b); // passing value to function printf("nValue of a: %d",a); printf("nValue of b: %d",b); } If you change the value of function parameter, it is changed for the current function only but it not change the value of variable inside the caller method
PARAMETER PASSING - CALL BY REFERENCE In call by reference, original value is changed or modified because we pass reference (address). Here, address of the value is passed in the function, so actual and formal arguments shares the same address space. Hence, any value changed inside the function, is reflected inside as well as outside the function.
PARAMETER PASSING - CALL BY REFERENCE #include<stdio.h> void swap(int *a, int *b) { int temp; temp=*a; *a=*b; *b=temp; } void main() { int a=100, b=200; swap(&a, &b); // passing value to function printf("nValue of a: %d",a); printf("nValue of b: %d",b); }
PARAMETER PASSING – CALL BY VALUE AND CALL BY REFERENCE Difference between call by value and call by reference. CALL BY VALUE CALL BY REFERENCE This method copy original value into function as a arguments. This method copy address of arguments into function as a arguments. Changes made to the parameter inside the function have no effect on the argument. Changes made to the parameter affect the argument. Because address is used to access the actual argument. Actual and formal arguments will be created in different memory location Actual and formal arguments will be created in same memory location
SUMMARY •The basic purpose of the function is code reuse. •From any function we can invoke (call) any another functions. •Always compilation will be take place from top to bottom. •Always execution process will starts from main() and ends with main() only. •In implementation when we are calling a function which is define later for avoiding the compilation error we need to for forward declaration that is prototype is required. •In function definition first line is called function declaration or function header. •Always function declaration should be match with function declaratory. •In implementation whenever a function does not returns any values back to the calling place then specify the return type. •Void means nothing that is no return value. •In implementation whenever a function returns other than void then specify the return type as return value type that is on e type of return value it is returning same type of return statement should be mentioned. •Default return type of any function is an int.
#include<stdio.h> Void takevalue(); Void sum(); Void takevalue() { Int a,b; Printf(“enter 2 values”); Scanf(“%d %d”,&a,&b); } Void sum() { takevalue(); Int c; C=a+b; Return c; } Void main() { sum(); Printf(“The sum is %d”, c); }
RECURSION Recursion is expressing an entity in terms of itself. In C programming, recursion is achieved using functions known as recursive function. Recursive functions are very powerful in solving and expressing complex mathematical problems. 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.
RECURSION VS ITERATION Basis For Comparison Recursion Iteration Basic The statement in a body of function calls the function itself. Allows the set of instructions to be repeatedly executed. Format In recursive function, only termination condition (base case) is specified. Iteration includes initialization, condition, execution of statement within loop and update (increments and decrements) the control variable. Termination A conditional statement is included in the body of the function to force the function to return without recursion call being executed. The iteration statement is repeatedly executed until a certain condition is reached. Condition If the function does not converge to some condition called (base case), it leads to infinite recursion. If the control condition in the iteration statement never become false, it leads to infinite iteration. Infinite Repetition Infinite recursion can crash the system. Infinite loop uses CPU cycles repeatedly. Applied Recursion is always applied to functions. Iteration is applied to iteration statements or "loops". Stack The stack is used to store the set of new local variables and parameters each time the function is called. Does not uses stack. Overhead Recursion possesses the overhead of repeated function calls. No overhead of repeated function call. Speed Slow in execution. Fast in execution. Size of Code Recursion reduces the size of the code. Iteration makes the code longer.
RECURSION VS ITERATION Recursion happens when a function calls a copy of itself to work on a smaller problem. Any function which calls itself is called recursive function, and such function calls are called recursive calls. Recursion involves several numbers of recursive calls, but it is important to impose a termination condition of recursion. Recursion code is shorter than iterative code however it is difficult to understand. Recursion cannot be applied to all the problem, but it is more useful for the tasks that can be defined in terms of similar subtasks. For Example, recursion may be applied to sorting, searching, and traversal problems. Iterative solutions are more efficient than recursion since function call is always overhead. Any problem that can be solved recursively, can also be solved iteratively. But some problems are best suited to be solved by the recursion, for example, tower of Hanoi, Fibonacci series, factorial finding, etc.
EXAMPLE #include <stdio.h> int fact (int); int main() { int n,f; printf("Enter the number whose factorial you want to calculate?"); scanf("%d",&n); f = fact(n); printf("factorial = %d",f); }
EXAMPLE int fact(int n) { if (n==0) { return 0; } else if ( n == 1) { return 1; } else { return n*fact(n-1); } }
WORKING
RECURSIVE FUNCTION A recursive function performs the tasks by dividing it into the subtasks. There is a termination condition defined in the function which is satisfied by some specific subtask. After this, the recursion stops and the final result is returned from the function. The case at which the function doesn't recur is called the base case whereas the instances where the function keeps calling itself to perform a subtask, is called the recursive case. All the recursive functions can be written using this format. Pseudocode for writing any recursive function is given below.
PSEUDOCODE FOR WRITING ANY RECURSIVE FUNCTION IS GIVEN BELOW if (test_for_base) { return some_value; } else if (test_for_another_base) { return some_another_value; } else { // Statements; recursive call; }
MEMORY ALLOCATION OF RECURSIVE METHOD Each recursive call creates a new copy of that method in the memory. Once some data is returned by the method, the copy is removed from the memory. Since all the variables and other stuff declared inside function get stored in the stack, therefore a separate stack is maintained at each recursive call. Once the value is returned from the corresponding function, the stack gets destroyed. Recursion involves so much complexity in resolving and tracking the values at each recursive call. Therefore we need to maintain the stack and track the values of the variables defined in the stack.
MEMORY ALLOCATION OF RECURSIVE METHOD Let us consider the following example to understand the memory allocation of the recursive functions. int display (int n) { if(n == 0) return 0; // terminating condition else { printf("%d",n); return display(n-1); // recursive call } } recursive function for n = 4. First, all the stacks are maintained which prints the corresponding value of n until n becomes 0, Once the termination condition is reached, the stacks get destroyed one by one by returning 0 to its calling stack. Consider the following image for more information regarding the stack trace for the recursive functions.
MEMORY ALLOCATION OF RECURSIVE METHOD
TYPES OF RECURSION Recursion are mainly of two types depending on whether a function calls itself from within itself or more than one function call one another mutually. The first one is called direct recursion and another one is called indirect recursion. Direct Recursion: These can be further categorized into four types: 1. Tail Recursion: If a recursive function calling itself and that recursive call is the last statement in the function then it’s known as Tail Recursion. After that call the recursive function performs nothing. The function has to process or perform any operation at the time of calling and it does nothing at returning time. Tail Recursion occurs if a recursive function calls itself (Direct Recursion) and the function call is the last statement or step to be processed in the function before returning having reached the base case. After processing the call the function returns control back to the parent function call. It is during the time of function call the
TYPES OF RECURSION-TAIL RECURSION // Code Showing Tail Recursion #include <stdio.h> // Recursion function void fun(int n) { if (n > 0) { printf("%d ", n); // Last statement in the function fun(n - 1); } } // Driver Code int main() { int x = 3; fun(x); return 0; }
TYPES OF RECURSION-TAIL RECURSION
TYPES OF RECURSION- HEAD RECURSION 2. Head Recursion: If a recursive function calling itself and that recursive call is the first statement in the function then it’s known as Head Recursion. There’s no statement, no operation before the call. The function doesn’t have to process or perform any operation at the time of calling and all operations are done at returning time. A recursive function is said to be Non-Tail, if the recursive call to the same function is not the last statement or the last step processed by the function. After returning back from the call stack there is some code left to evaluate. In the case, of a function, the recursive call is the first statement
TYPES OF RECURSION- HEAD RECURSION // C program showing Head Recursion #include <stdio.h> // Recursive function void fun(int n) { if (n > 0) { // First statement in the function fun(n - 1); printf("%d ", n); } } // Driver code int main() { int x = 3; fun(x); return 0; }
TYPES OF RECURSION-HEAD RECURSION
TYPES OF RECURSION-HEAD RECURSION Tail-recursive functions are considered far better than non-tail recursive functions as they can be further optimized by the compiler. Since the recursive call is the last statement, there is nothing left to do in the current function, so the compiler does not save the current function call in the call stack.
TYPES OF RECURSION-TREE RECURSION 3. Tree Recursion: To understand Tree Recursion let’s first understand Linear Recursion. If a recursive function calling itself for one time then it’s known as Linear Recursion. Otherwise if a recursive function calling itself for more than one time then it’s known as Tree Recursion. fun(n) { if(n>0) { // some code fun(n-1); // Calling itself only once { //some code }
TYPES OF RECURSION-TREE RECURSION The recursion in which the function calling itself calls for one more than time inside it’s block, is called a Tree Recursion. If the call is made only once inside the function block then, it is termed as Linear Recursion. A famous example of this type of recursion is in Nth Fibonacci Number problem, where given a number we have to find the nth term value in Fibonacci series.
TYPES OF RECURSION-TREE RECURSION //Program to generate Nth Fibonacci Number showing Tree-Recursion #include<stdio.h> int fib(int n) { // Base Case if (n <= 1) return n; return fib(n-1) + fib(n-2); } void main() { int n = 4; printf("%d", fib(4)); }
TYPES OF RECURSION-TREE RECURSION
TYPES OF RECURSION-TREE RECURSION // C program to show Tree Recursion #include <stdio.h> // Recursive function void fun(int n) { if (n > 0) { printf("%d ", n); // Calling once fun(n - 1); // Calling twice fun(n - 1); } } // Driver code int main() { fun(3); return 0; }
TYPES OF RECURSION-TREE RECURSION
TYPES OF RECURSION-NESTED RECURSION Nested Recursion: In this recursion, a recursive function will pass the parameter as a recursive call. That means “recursion inside recursion”. // C program to show Nested Recursion #include <stdio.h> int fun(int n) { if (n > 100) return n - 10; // A recursive function passing parameter // as a recursive call or recursion // inside the recursion return fun(fun(n + 11)); } // Driver code int main() { int r; r = fun(95); printf("%dn", r); return 0; }
TYPES OF RECURSION-NESTED RECURSION
TYPES OF RECURSION-INDIRECT RECURSION Indirect Recursion: In this recursion, there may be more than one functions and they are calling one another in a circular manner. fun(A) is calling for fun(B), fun(B) is calling for fun(C) and fun(C) is calling for fun(A) and thus it makes a cycle.
TYPES OF RECURSION-INDIRECT RECURSION // C program to show Indirect Recursion #include <stdio.h> void funB(int n); void funA(int n) { if (n > 0) { printf("%d ", n); // Fun(A) is calling fun(B) funB(n - 1); } } void funB(int n) { if (n > 1) { printf("%d ", n); // Fun(B) is calling fun(A) funA(n / 2); } } // Driver code int main() { funA(20); return 0; }
TYPES OF RECURSION-INDIRECT RECURSION
DISADVANTAGES OF RECURSION What is the disadvantage of recursion? The memory is incremented by the number of times a recursive function is called. This is one of the drawbacks/disadvantages of recursion. When to (not) use recursion? If the memory utilization is the concern of if there is limited memory resource available, it is always a good choice implementing primitive type recursion with loops. Mobile has very limited memory space to execute any apps. If you are developing a mobile application, avoid using recursion.
STORAGE CLASSES IN C Storage classes in C are used to determine the lifetime, visibility, memory location, and initial value of a variable. There are four types of storage classes in C Automatic External Static Register
STORAGE CLASSES IN C Storage Classes Storage Place Default Value Scope Lifetime auto RAM Garbage Value Local Within function extern RAM Zero Global Till the end of the main program Maybe declared anywhere in the program static RAM Zero Local Till the end of the main program, Retains value between multiple functions call register Register Garbage Value Local Within the function
STORAGE CLASSES - AUTO Automatic Automatic variables are allocated memory automatically at runtime. The visibility of the automatic variables is limited to the block in which they are defined. The scope of the automatic variables is limited to the block in which they are defined. The automatic variables are initialized to garbage by default. The memory assigned to automatic variables gets freed upon exiting from the block. The keyword used for defining automatic variables is auto. Every local variable is automatic in C by default.
STORAGE CLASSES - AUTO #include <stdio.h> int main() { int a; //auto char b; float c; printf("%d %c %f",a,b,c); // printing initial default value of automatic variables a, b, and c. return 0; }
STORAGE CLASSES - STATIC The variables defined as static specifier can hold their value between the multiple function calls. Static local variables are visible only to the function or the block in which they are defined. A same static variable can be declared many times but can be assigned at only one time. Default initial value of the static integral variable is 0 otherwise null. The visibility of the static global variable is limited to the file in which it has declared. The keyword used to define static variable is static.
STORAGE CLASSES - STATIC #include<stdio.h> static char c; static int i; static float f; static char s[100]; void main () { printf("%d %d %f %s",c,i,f); // the initial default value of c, i, and f will be printed. }
STORAGE CLASSES - REGISTER The variables defined as the register is allocated the memory into the CPU registers depending upon the size of the memory remaining in the CPU. We can not dereference the register variables, i.e., we can not use &operator for the register variable. The access time of the register variables is faster than the automatic variables. The initial default value of the register local variables is garbage value. The register keyword is used for the variable which should be stored in the CPU register. However, it is compiler’s choice whether or not; the variables can be stored in the register. We can store pointers into the register, i.e., a register can store the address of a variable. Static variables can not be stored into the register since we can not use more than one storage specifier for the same variable.
STORAGE CLASSES - REGISTER #include <stdio.h> int main() { register int a; // variable a is allocated memory in the CPU register. The initial default value of a is garbage printf("%d",a); return 0; }
STORAGE CLASSES - EXTERN The external storage class is used to tell the compiler that the variable defined as extern is declared with an external linkage elsewhere in the program. The variables declared as extern are not allocated any memory. It is only declaration and intended to specify that the variable is declared elsewhere in the program. The default initial value of external integral type is 0 otherwise null. We can only initialize the extern variable globally, i.e., we can not initialize the external variable within any block or method. An external variable can be declared many times but can be initialized at only once. If a variable is declared as external then the compiler searches for that variable to be initialized somewhere in the program which may
STORAGE CLASSES - EXTERN #include <stdio.h> int main() { extern int a; printf("%d",a); }
MEMORY MANAGEMENT IN C
PROBLEMS 1. Write a recursive function to calculate 1+2+3+...+n 2. Write a function to check whether a given integer is a square number or not. Eg. 4 , 9 , 16 , 25 etc 3. Using recursion write a program to find octal , binary and hexadecimal equivalent of the natural (decimal) number entered by the user

Module 3-Functions

  • 1.
    MODULE 3: FUNCTIONS CO3:Decompose a problem into functions and synthesize a complete program.
  • 2.
    TOPICS TO BECOVERED Introduction to functions Function prototype/declaration Function definition Accessing a function Parameter passing Recursion
  • 3.
    INTRODUCTION A function isa group of statements that together perform a task. Every C program has at least one function, which is main() You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division is such that each function performs a specific task. A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function. A function is a block of code that performs a specific task. Suppose, you need to create a program to draw a circle and color it. You can create two functions to solve this problem:  Create draw circle function  create a color function Dividing a complex problem into smaller chunks makes our program easy to understand and reuse.
  • 4.
    INTRODUCTION Types of function Thereare two types of function in C programming: Standard library functions User-defined functions
  • 5.
    INTRODUCTION Standard library functions Thestandard library functions are built-in functions in C programming. These functions are defined in header files. For example, •printf() •It is a standard library function to send formatted output to the screen (display output on the screen). •This function is defined in the stdio.h header file. •Hence, to use the printf() function, we need to include the stdio.h header file using #include <stdio.h>. • sqrt() •This function calculates the square root of a number. The function is defined in the math.h header file.
  • 6.
    INTRODUCTION Library functions arethose functions which are already defined in C library such as strcat(), printf(), scanf() etc. You just need to include appropriate header files to use these functions. The prototype and data definitions of these functions are present in their respective header files. To use these functions we need to include the header file in our program. For example, If you want to use the printf() function, the header file <stdio.h> should be included. If you try to use printf() without including the stdio.h header file, you will get an error
  • 7.
    INTRODUCTION User-defined function User-defined functionsare those functions which are defined by the user. These functions are made for code reusability and for saving time and space. You can also create functions as per your need. Such functions created by the user are known as user-defined functions. How user-defined function works? #include <stdio.h> void functionName() { ... .. ... ... .. ... } int main() { ... .. ... ... .. ... functionName(); ... .. ... ... .. ... }
  • 8.
    INTRODUCTION The execution ofa C program begins from the main() function. When the compiler encounters functionName();, control of the program jumps to void functionName() And, the compiler starts executing the codes inside functionName(). The control of the program jumps back to the main() function once code inside the function definition is executed .
  • 9.
    INTRODUCTION Advantages of user-definedfunction The program will be easier to understand, maintain (add features later on) ,change and debug. Reusable codes that can be used in other programs A large program can be divided into smaller modules. Hence, a large project can be divided among many programmers.
  • 10.
    FUNCTION DECLARATION Function Declaration: Syntaxof function declaration: return_type function_name (data_type arg1, data_type arg2); int add(int x, int y); //function declaration In Function Declaration, we specify the name of the function, the number of input parameter, their data types & the return type of the function. Function declaration tells compiler about the list of arguments the function is expecting with their data types & the return type of the function. In function declaration, specifying the names of the parameter is optional, but specifying their data types is mandatory.
  • 11.
  • 12.
    FUNCTION DEFINITION int add(int,int); //function declaration return_type function_name(parameters) { Function body } a function definition consists of two parts i.e. function header & function body
  • 13.
    FUNCTION DEFINITION Function Header:function header is same as function declaration without the semicolon. Function header contains function name, parameter & return type.  Return Type: Return type is the data type of the value which will be returned by the function. The function may or may not return a value. If it does then the data type of the retuning value should be specified, otherwise the return type needs to be void.  Function Name: This is the name of the function using which we can call the function when & where needed.  Parameters: The parameters are the input values which will be passed to the function. It tells about the data types of the arguments, their order and the number of arguments that will be passed to the function. The parameters are optional. You can also have functions without parameters.
  • 14.
    FUNCTION DEFINITION Function Body:The function body is the set of statement which performs a specific task. It defines what the function does. int add(int x, int y) { int sum = x+y; return(sum); } It is recommended to declare a function before we define & use it. In C, we can declare & define the function at the same place.
  • 15.
    FUNCTION ARGUMENTS There aretwo types of parameter: Actual Parameter: Those parameters which are passed to functions while calling them is are known as actual parameter. For example, 23 & 31 in the above example are the actual parameters. Formal Parameter: Those parameters which are received by the functions are known as formal parameters. For example, x & y in the above example are the formal parameters.
  • 16.
    TYPES OF USER-DEFINED FUNCTIONS 1.No arguments passed and no return value 2. No arguments passed but a return value 3. Argument passed but no return value 4. Argument passed and a return value
  • 17.
    TYPES OF USER-DEFINED FUNCTIONS 1.No arguments passed and no return value Function with no return no argument, neither returns a value nor accepts any argument. This type of function does not communicate with the caller function. It works as an independent working block. Use this type of function when you have some task to do independent of the caller function. You must add void as function return type for this type of function.
  • 18.
    TYPES OF USER-DEFINED FUNCTIONS 1.No arguments passed and no return value Syntax to define function with no return no argument void function_name() { // Function body }
  • 19.
    TYPES OF USER-DEFINED FUNCTIONS 1.No arguments passed and no return value #include <stdio.h> void add(); void add() { int x = 20; int y = 30; int sum = x+y; printf("sum %d", sum); } int main() { add(); return 0; }
  • 20.
    TYPES OF USER-DEFINED FUNCTIONS 2.No arguments passed but a return value Function with return but no arguments, returns a value but does not accept any argument. This type of function communicates with the caller function by returning value back to the caller. Syntax to define function with return but no arguments return_type function_name() { // Function body return some_value; } Where return_type and some_value must be declared with same type.
  • 21.
    TYPES OF USER-DEFINED FUNCTIONS 2.No arguments passed but a return value #include <stdio.h> int add(); int add() { int x = 20; int y = 30; int sum = x+y; return(sum); } int main() { int sum; sum = add(); printf("sum %d", sum); return 0; }
  • 22.
    TYPES OF USER-DEFINED FUNCTIONS 3.Argument passed but no return value Function with no return but with arguments, does not return a value but accepts arguments as input. For this type of function you must define function return type as void. Syntax to define function with no return but with arguments void function_name(type arg1, type arg2, ...) { // Function body } Where type is a valid C data type and argN is a valid C identifier.
  • 23.
    TYPES OF USER-DEFINED FUNCTIONS 3.Argument passed but no return value #include <stdio.h> void add(int, int); void add(int x, int y) { int sum = x+y; return(sum); } int main() { add(23, 31); return 0; }
  • 24.
    TYPES OF USER-DEFINED FUNCTIONS 4.Argument passed and a return value Function with return and arguments, returns a value and may accept arguments. Since the function accepts input and returns a result to the caller, hence this type of functions are dependent on each other. Syntax to define function with return and arguments return_type function_name(type arg1, type arg2, ...) { // Function body return some_variable; }
  • 25.
    TYPES OF USER-DEFINED FUNCTIONS 4.Argument passed and a return value #include <stdio.h> int add(int, int); int add(int x, int y) { int sum = x+y; return(sum); } int main() { int sum = add(23, 31); printf("%d", sum); return 0; }
  • 26.
    PARAMETER PASSING Function argumentsare the inputs passed to a function. A function must declare variables to accept passed arguments. A variable that accepts function argument is known as function parameter. A function argument is commonly referred as actual parameter and function parameter is referred as formal parameter.
  • 27.
    PARAMETER PASSING In Cprogramming you can pass value to a function in two ways. 1. Call by value 2. Call by reference These two ways are generally differentiated by the type of values passed to them as parameters. The parameters passed to function are called actual parameters whereas the parameters received by function are called formal parameters.
  • 28.
  • 29.
  • 30.
    PARAMETER PASSING –CALL BY VALUE Call by value is the default mechanism to pass arguments to a function. In Call by value, during function call actual parameter value is copied and passed to formal parameter. Changes made to the formal parameters does not affect the actual parameter. 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 the caller.
  • 31.
    PARAMETER PASSING –CALL BY VALUE #include<stdio.h> void swap(int a, int b) { int temp; temp=a; a=b; b=temp; } void main() { int a=100, b=200; swap(a, b); // passing value to function printf("nValue of a: %d",a); printf("nValue of b: %d",b); } If you change the value of function parameter, it is changed for the current function only but it not change the value of variable inside the caller method
  • 32.
    PARAMETER PASSING -CALL BY REFERENCE In call by reference, original value is changed or modified because we pass reference (address). Here, address of the value is passed in the function, so actual and formal arguments shares the same address space. Hence, any value changed inside the function, is reflected inside as well as outside the function.
  • 33.
    PARAMETER PASSING -CALL BY REFERENCE #include<stdio.h> void swap(int *a, int *b) { int temp; temp=*a; *a=*b; *b=temp; } void main() { int a=100, b=200; swap(&a, &b); // passing value to function printf("nValue of a: %d",a); printf("nValue of b: %d",b); }
  • 34.
    PARAMETER PASSING –CALL BY VALUE AND CALL BY REFERENCE Difference between call by value and call by reference. CALL BY VALUE CALL BY REFERENCE This method copy original value into function as a arguments. This method copy address of arguments into function as a arguments. Changes made to the parameter inside the function have no effect on the argument. Changes made to the parameter affect the argument. Because address is used to access the actual argument. Actual and formal arguments will be created in different memory location Actual and formal arguments will be created in same memory location
  • 35.
    SUMMARY •The basic purposeof the function is code reuse. •From any function we can invoke (call) any another functions. •Always compilation will be take place from top to bottom. •Always execution process will starts from main() and ends with main() only. •In implementation when we are calling a function which is define later for avoiding the compilation error we need to for forward declaration that is prototype is required. •In function definition first line is called function declaration or function header. •Always function declaration should be match with function declaratory. •In implementation whenever a function does not returns any values back to the calling place then specify the return type. •Void means nothing that is no return value. •In implementation whenever a function returns other than void then specify the return type as return value type that is on e type of return value it is returning same type of return statement should be mentioned. •Default return type of any function is an int.
  • 36.
    #include<stdio.h> Void takevalue(); Void sum(); Voidtakevalue() { Int a,b; Printf(“enter 2 values”); Scanf(“%d %d”,&a,&b); } Void sum() { takevalue(); Int c; C=a+b; Return c; } Void main() { sum(); Printf(“The sum is %d”, c); }
  • 37.
    RECURSION Recursion is expressingan entity in terms of itself. In C programming, recursion is achieved using functions known as recursive function. Recursive functions are very powerful in solving and expressing complex mathematical problems. 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.
  • 38.
    RECURSION VS ITERATION BasisFor Comparison Recursion Iteration Basic The statement in a body of function calls the function itself. Allows the set of instructions to be repeatedly executed. Format In recursive function, only termination condition (base case) is specified. Iteration includes initialization, condition, execution of statement within loop and update (increments and decrements) the control variable. Termination A conditional statement is included in the body of the function to force the function to return without recursion call being executed. The iteration statement is repeatedly executed until a certain condition is reached. Condition If the function does not converge to some condition called (base case), it leads to infinite recursion. If the control condition in the iteration statement never become false, it leads to infinite iteration. Infinite Repetition Infinite recursion can crash the system. Infinite loop uses CPU cycles repeatedly. Applied Recursion is always applied to functions. Iteration is applied to iteration statements or "loops". Stack The stack is used to store the set of new local variables and parameters each time the function is called. Does not uses stack. Overhead Recursion possesses the overhead of repeated function calls. No overhead of repeated function call. Speed Slow in execution. Fast in execution. Size of Code Recursion reduces the size of the code. Iteration makes the code longer.
  • 39.
    RECURSION VS ITERATION Recursionhappens when a function calls a copy of itself to work on a smaller problem. Any function which calls itself is called recursive function, and such function calls are called recursive calls. Recursion involves several numbers of recursive calls, but it is important to impose a termination condition of recursion. Recursion code is shorter than iterative code however it is difficult to understand. Recursion cannot be applied to all the problem, but it is more useful for the tasks that can be defined in terms of similar subtasks. For Example, recursion may be applied to sorting, searching, and traversal problems. Iterative solutions are more efficient than recursion since function call is always overhead. Any problem that can be solved recursively, can also be solved iteratively. But some problems are best suited to be solved by the recursion, for example, tower of Hanoi, Fibonacci series, factorial finding, etc.
  • 40.
    EXAMPLE #include <stdio.h> int fact(int); int main() { int n,f; printf("Enter the number whose factorial you want to calculate?"); scanf("%d",&n); f = fact(n); printf("factorial = %d",f); }
  • 41.
    EXAMPLE int fact(int n) {if (n==0) { return 0; } else if ( n == 1) { return 1; } else { return n*fact(n-1); } }
  • 42.
  • 43.
    RECURSIVE FUNCTION A recursivefunction performs the tasks by dividing it into the subtasks. There is a termination condition defined in the function which is satisfied by some specific subtask. After this, the recursion stops and the final result is returned from the function. The case at which the function doesn't recur is called the base case whereas the instances where the function keeps calling itself to perform a subtask, is called the recursive case. All the recursive functions can be written using this format. Pseudocode for writing any recursive function is given below.
  • 44.
    PSEUDOCODE FOR WRITINGANY RECURSIVE FUNCTION IS GIVEN BELOW if (test_for_base) { return some_value; } else if (test_for_another_base) { return some_another_value; } else { // Statements; recursive call; }
  • 45.
    MEMORY ALLOCATION OF RECURSIVEMETHOD Each recursive call creates a new copy of that method in the memory. Once some data is returned by the method, the copy is removed from the memory. Since all the variables and other stuff declared inside function get stored in the stack, therefore a separate stack is maintained at each recursive call. Once the value is returned from the corresponding function, the stack gets destroyed. Recursion involves so much complexity in resolving and tracking the values at each recursive call. Therefore we need to maintain the stack and track the values of the variables defined in the stack.
  • 46.
    MEMORY ALLOCATION OF RECURSIVEMETHOD Let us consider the following example to understand the memory allocation of the recursive functions. int display (int n) { if(n == 0) return 0; // terminating condition else { printf("%d",n); return display(n-1); // recursive call } } recursive function for n = 4. First, all the stacks are maintained which prints the corresponding value of n until n becomes 0, Once the termination condition is reached, the stacks get destroyed one by one by returning 0 to its calling stack. Consider the following image for more information regarding the stack trace for the recursive functions.
  • 47.
  • 48.
    TYPES OF RECURSION Recursionare mainly of two types depending on whether a function calls itself from within itself or more than one function call one another mutually. The first one is called direct recursion and another one is called indirect recursion. Direct Recursion: These can be further categorized into four types: 1. Tail Recursion: If a recursive function calling itself and that recursive call is the last statement in the function then it’s known as Tail Recursion. After that call the recursive function performs nothing. The function has to process or perform any operation at the time of calling and it does nothing at returning time. Tail Recursion occurs if a recursive function calls itself (Direct Recursion) and the function call is the last statement or step to be processed in the function before returning having reached the base case. After processing the call the function returns control back to the parent function call. It is during the time of function call the
  • 49.
    TYPES OF RECURSION-TAIL RECURSION //Code Showing Tail Recursion #include <stdio.h> // Recursion function void fun(int n) { if (n > 0) { printf("%d ", n); // Last statement in the function fun(n - 1); } } // Driver Code int main() { int x = 3; fun(x); return 0; }
  • 50.
  • 51.
    TYPES OF RECURSION-HEAD RECURSION 2. Head Recursion: If a recursive function calling itself and that recursive call is the first statement in the function then it’s known as Head Recursion. There’s no statement, no operation before the call. The function doesn’t have to process or perform any operation at the time of calling and all operations are done at returning time. A recursive function is said to be Non-Tail, if the recursive call to the same function is not the last statement or the last step processed by the function. After returning back from the call stack there is some code left to evaluate. In the case, of a function, the recursive call is the first statement
  • 52.
    TYPES OF RECURSION-HEAD RECURSION // C program showing Head Recursion #include <stdio.h> // Recursive function void fun(int n) { if (n > 0) { // First statement in the function fun(n - 1); printf("%d ", n); } } // Driver code int main() { int x = 3; fun(x); return 0; }
  • 53.
  • 54.
    TYPES OF RECURSION-HEAD RECURSION Tail-recursivefunctions are considered far better than non-tail recursive functions as they can be further optimized by the compiler. Since the recursive call is the last statement, there is nothing left to do in the current function, so the compiler does not save the current function call in the call stack.
  • 55.
    TYPES OF RECURSION-TREE RECURSION 3.Tree Recursion: To understand Tree Recursion let’s first understand Linear Recursion. If a recursive function calling itself for one time then it’s known as Linear Recursion. Otherwise if a recursive function calling itself for more than one time then it’s known as Tree Recursion. fun(n) { if(n>0) { // some code fun(n-1); // Calling itself only once { //some code }
  • 56.
    TYPES OF RECURSION-TREE RECURSION Therecursion in which the function calling itself calls for one more than time inside it’s block, is called a Tree Recursion. If the call is made only once inside the function block then, it is termed as Linear Recursion. A famous example of this type of recursion is in Nth Fibonacci Number problem, where given a number we have to find the nth term value in Fibonacci series.
  • 57.
    TYPES OF RECURSION-TREE RECURSION //Programto generate Nth Fibonacci Number showing Tree-Recursion #include<stdio.h> int fib(int n) { // Base Case if (n <= 1) return n; return fib(n-1) + fib(n-2); } void main() { int n = 4; printf("%d", fib(4)); }
  • 58.
  • 59.
    TYPES OF RECURSION-TREE RECURSION //C program to show Tree Recursion #include <stdio.h> // Recursive function void fun(int n) { if (n > 0) { printf("%d ", n); // Calling once fun(n - 1); // Calling twice fun(n - 1); } } // Driver code int main() { fun(3); return 0; }
  • 60.
  • 61.
    TYPES OF RECURSION-NESTED RECURSION NestedRecursion: In this recursion, a recursive function will pass the parameter as a recursive call. That means “recursion inside recursion”. // C program to show Nested Recursion #include <stdio.h> int fun(int n) { if (n > 100) return n - 10; // A recursive function passing parameter // as a recursive call or recursion // inside the recursion return fun(fun(n + 11)); } // Driver code int main() { int r; r = fun(95); printf("%dn", r); return 0; }
  • 62.
  • 63.
    TYPES OF RECURSION-INDIRECT RECURSION IndirectRecursion: In this recursion, there may be more than one functions and they are calling one another in a circular manner. fun(A) is calling for fun(B), fun(B) is calling for fun(C) and fun(C) is calling for fun(A) and thus it makes a cycle.
  • 64.
    TYPES OF RECURSION-INDIRECT RECURSION //C program to show Indirect Recursion #include <stdio.h> void funB(int n); void funA(int n) { if (n > 0) { printf("%d ", n); // Fun(A) is calling fun(B) funB(n - 1); } } void funB(int n) { if (n > 1) { printf("%d ", n); // Fun(B) is calling fun(A) funA(n / 2); } } // Driver code int main() { funA(20); return 0; }
  • 65.
  • 66.
    DISADVANTAGES OF RECURSION Whatis the disadvantage of recursion? The memory is incremented by the number of times a recursive function is called. This is one of the drawbacks/disadvantages of recursion. When to (not) use recursion? If the memory utilization is the concern of if there is limited memory resource available, it is always a good choice implementing primitive type recursion with loops. Mobile has very limited memory space to execute any apps. If you are developing a mobile application, avoid using recursion.
  • 67.
    STORAGE CLASSES INC Storage classes in C are used to determine the lifetime, visibility, memory location, and initial value of a variable. There are four types of storage classes in C Automatic External Static Register
  • 68.
    STORAGE CLASSES INC Storage Classes Storage Place Default Value Scope Lifetime auto RAM Garbage Value Local Within function extern RAM Zero Global Till the end of the main program Maybe declared anywhere in the program static RAM Zero Local Till the end of the main program, Retains value between multiple functions call register Register Garbage Value Local Within the function
  • 69.
    STORAGE CLASSES -AUTO Automatic Automatic variables are allocated memory automatically at runtime. The visibility of the automatic variables is limited to the block in which they are defined. The scope of the automatic variables is limited to the block in which they are defined. The automatic variables are initialized to garbage by default. The memory assigned to automatic variables gets freed upon exiting from the block. The keyword used for defining automatic variables is auto. Every local variable is automatic in C by default.
  • 70.
    STORAGE CLASSES -AUTO #include <stdio.h> int main() { int a; //auto char b; float c; printf("%d %c %f",a,b,c); // printing initial default value of automatic variables a, b, and c. return 0; }
  • 71.
    STORAGE CLASSES -STATIC The variables defined as static specifier can hold their value between the multiple function calls. Static local variables are visible only to the function or the block in which they are defined. A same static variable can be declared many times but can be assigned at only one time. Default initial value of the static integral variable is 0 otherwise null. The visibility of the static global variable is limited to the file in which it has declared. The keyword used to define static variable is static.
  • 72.
    STORAGE CLASSES -STATIC #include<stdio.h> static char c; static int i; static float f; static char s[100]; void main () { printf("%d %d %f %s",c,i,f); // the initial default value of c, i, and f will be printed. }
  • 73.
    STORAGE CLASSES -REGISTER The variables defined as the register is allocated the memory into the CPU registers depending upon the size of the memory remaining in the CPU. We can not dereference the register variables, i.e., we can not use &operator for the register variable. The access time of the register variables is faster than the automatic variables. The initial default value of the register local variables is garbage value. The register keyword is used for the variable which should be stored in the CPU register. However, it is compiler’s choice whether or not; the variables can be stored in the register. We can store pointers into the register, i.e., a register can store the address of a variable. Static variables can not be stored into the register since we can not use more than one storage specifier for the same variable.
  • 74.
    STORAGE CLASSES -REGISTER #include <stdio.h> int main() { register int a; // variable a is allocated memory in the CPU register. The initial default value of a is garbage printf("%d",a); return 0; }
  • 75.
    STORAGE CLASSES -EXTERN The external storage class is used to tell the compiler that the variable defined as extern is declared with an external linkage elsewhere in the program. The variables declared as extern are not allocated any memory. It is only declaration and intended to specify that the variable is declared elsewhere in the program. The default initial value of external integral type is 0 otherwise null. We can only initialize the extern variable globally, i.e., we can not initialize the external variable within any block or method. An external variable can be declared many times but can be initialized at only once. If a variable is declared as external then the compiler searches for that variable to be initialized somewhere in the program which may
  • 76.
    STORAGE CLASSES -EXTERN #include <stdio.h> int main() { extern int a; printf("%d",a); }
  • 77.
  • 78.
    PROBLEMS 1. Write arecursive function to calculate 1+2+3+...+n 2. Write a function to check whether a given integer is a square number or not. Eg. 4 , 9 , 16 , 25 etc 3. Using recursion write a program to find octal , binary and hexadecimal equivalent of the natural (decimal) number entered by the user