Presentation is loading. Please wait.

Presentation is loading. Please wait.

Functions Function: The strength of C language is to define and use function. The strength of C language is that C function are easy to define and use.

Similar presentations

Presentation on theme: "Functions Function: The strength of C language is to define and use function. The strength of C language is that C function are easy to define and use."— Presentation transcript:

1 Functions Function: The strength of C language is to define and use function. The strength of C language is that C function are easy to define and use. Function Library User define function function

2 Library function: The library function are not required to be written by us. Eg: printf scanf

3 User define function: This function as to be developed by the user at the time of writing a program. Eg: main() ‘main’ is specially used function in C. Ever program must have main function to indicate, where the program begins its execution. When a program to large and complex then the result of debugging testing and maintaining becomes difficult.

4 Advantages: It felicitate top down modular program. The length of the source program can be reduce by using functions at It is easy to locate and isolate and fault function easily A function can used by many other program, it means programmer built an what have already done, insert of starting over scratch.

5 Function 1 function 2 function3 function4
Main program Function function function3 function4

6 Using Functions The main functions and other library functions does need to be declared and defined but the main function’s body need to be defined by the programmer.

7 The 3 components associated with functions are:
The Declaration The function definition The Calling Statement

8 Function Declaration In C user- written functions should normally be declared prior to its use to allow compiler to perform type checking on arguments used in its call statement. The general form is: Retirn_data_type function_name (data_type Var_name, …..);

9 Function name: this is the name given to the function. It follows the same naming convention as that of any valid variable in C. Return data type: this specifies the type of data given back to the calling construct. Data type list: this list specifies the data type of each variables, the values of which are expected to be transmitted to the function. These variables are known as formal parameters.

10 Note: It is possible not to declare functions prior to the use but the error checking will not be performed. ; is required at the end of function declaration. E.g. int FindMax(int x, int y);

11 Function Definition The collection of program statements that does a specific tasks done by the function is called the function definition. It conist of function header: Int FindMax(int x, int y) { } and function body. //body of the function….

12 Function call The function is called from the main()
The function can in turn call a another function. the function call statements invokes the function, which means the program control passes to that function. Once the function completes its task, the program control is passed back to the calling environment.

13 The general form of calling stmt is:
Function_name (var1, var2,..); Or var_name=function name(var1, var2,..);

14 Salient points to be taken into consideration
The func name and the type and number of arguments must match with that of the function declaration stmt and the header of the function definition. Arguments present in the form of expression are evaluated and converted to the type of formal parameters at the beginning of the body of the function.

15 Passing of arguments to the function
Call by value or pass by value: When arguments are passed by values this means that local copies of the values of the arguments are passed to the function. Call by reference or pass by reference. The address of the variable is passed as value of parameters to the function.

16 E.g. int sum(int x, int y) { int ans = 0; //holds the answer that will be returned ans = x + y; //calculate the sum return ans //return the answer }

17 Program: #include<stdio.h> add(a,b); main() { int a,b,c; c=add(10,20); printf(); } add(a,b) int c; c=a+b; return c;

18 Passing arrays to functions
Arrays can also be the arguments of function Only the base address of the array is passed to the function Hence the passing of arguments is done by reference. When arrays is passed as arguments then actual contents of the arrays is altered.

19 #include<stdio.h> flaot avg_age(int[]); main() { Int I, b[5]; Float avgerage; Printf(“enter age of stud in team”); For(i=0;i<5;i++) Svanf(“%d”,&b[i]); Average=avg_age(b);

20 Printf((“the avg is %d”,average);
Return 0; } Float avg_age(int a[]) { Int j; Float sum=0; For(j=0;j<5;j++) Sum+=[j]; Return sum/5;

21 Scope of variables The scope rules related to functions basically relate to the accessibility, duration of existence, and the boundary of the usage of the variables declared within the block. Local scope Global scope

22 Storage Classes Storage classes specify the location where the variables will be stored: primary memory, registers of cpu of the computer. The general form is: <storage_class_spesifier> <data_type> <variable_name>;

23 Types of storage classes
Automatic External Register ststic

24 The automatic storage class
The variables declared within the body of variables are automatic Even if we do not include the keyword in function while declaring variables they are implicitly defined as automatic The auto is used to explicitly define a variable as automatic. These variables are stored in primary memory. This keyword is rarely used

25 External storage class
The keyword extern is used. It used to declare global variables which are accessible within different files and functions. The default value of such variable is zero. It is stored in primary memory.

26 //pgm1. c #include<stdio. h>] #include ”pgm2
//pgm1.c #include<stdio.h>] #include ”pgm2.c” Int I; Void show(); Int main() { i=10; Show(); Printf(“%d”,i); Return 0; }

27 //pgm2.c Extern int I; Show() { Printf(“%d”,i); }

28 The Register Storage Class
The variables stored in register of CPU are accessed in much lesser time. The keyword register is used. The default value is not known It is applicable to int and char only. The scope is limited upto the region or block or function in which it is defined.

29 Static Storage class The static storage class variable makes the variable permanent. Their can be local i.e. internal static variables and global i.e. external static variables. The default value is zero. They are stored in primary memory.

30 The external static variables in a program are declared like global variables with the keyword static. The static var are accessible by all functions in the program file where these variables exist and are declared. These variables are not accessible in the other files. These variables exist thru out the main program execution.

31 #include<stdio.h> Main() { Void show(); Printf(“\n first call”) Show(); Printf(“\n 2nd call”) Printf(“\n third call”) }

32 Void show() { Static int i; Printf(“%d”,i); i++; } Op: First call i=0; 2nd call i=1 3rd call i=2

33 Recursive Functions. Recursion in programming is a technique for defining a problem in terms of one or more smaller versions of the problem. A recursive function is one that calls itself directly or indirectly to solve a smaller version of its task until a final call which does not require a self call.

34 #include<stdio.h>
Void print_backward(); Main() { Printf(“Enter a character (‘.’) to end”); Print_backward(); } Void print_backward() Char ch; Scanf(“%c”,&ch); If(ch != ‘.’) Printf(“%c”, ch); i/p : hi o/p: ih

35 The mechanics of recursive call
Start main program ….. 1st call to print backward enter a char : H 2nd call to print_backward enter a char: i. 3rd call to print_backward enter a char: . //now it will not call againcoz its ‘.’ 3rd call finish print i. 2nd call finish Print H. First call Finish… End of main program………

36 How recursion is implemented.
The storage mechanism in most modern languages is stack storage mgmt. In this mechanism the program’s data area is allocated at load time. While storage for functions data is allocated when function is invoked. On exit from function this storage is de- allocated. This results in a runtime stack. In recursive cases one call does not overlap with the other.

37 What is need for implementing recursion
Decomposition into smaller problems of same size. Recursive call must diminish problem size. Necessity of base case. Base case must be reached.

38 What is a base case. An instance of a problem solution of which requires no further recursive calls is known as base case. It is special case whose solution is known. Every recursive algo requires at least one base case in order to be valid.

39 The purpose of base case
It terminates the condition. Without an explicitly defined base case, a recursive function would call itself indefinitely.

40 Program to find factorial of a number using recursive function.
#include<stdio.h> Long int factorial(int no); Main() { Int I; Printf(“enter number”); Sancf(“%d”,&i); Printf(“factorial of %d is %ld”, I, factorial(i)); }

41 Long int factorial(int n)
{ If(n==0) Return 1; Else Return (n * factorial(n-1)); } I/P: 3 o/p: 6

42 N->3 3==0 false Ans = 3* factorial (3-1)//2 n=2; 2==0 false Ans=2*factorial(2-1)//1 n=1 1==0 false Ans =1 * factorial (1-1)//0 n=0; 0==0 true… return 1; Ans=1*1 Return 1; Ans=2*1; Return 2; Ans=3*2; Return 6.

43 Comparing recursion and iteration
Recursion is like top-down approach to problem solving. Iteration is more bottom up approach Recursion can require substantial amount of overhead.


Download ppt "Functions Function: The strength of C language is to define and use function. The strength of C language is that C function are easy to define and use."

Similar presentations

Ads by Google