450 likes | 599 Views
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. Library function:
E N D
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
Library function: The library function are not required to be written by us. Eg: printf scanf
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.
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.
Main program Function 1 function 2 function3 function4
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.
The 3 components associated with functions are: • The Declaration • The function definition • The Calling Statement
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, …..);
http://gtu-mca.blogspot.com • 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.
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);
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: • IntFindMax(int x, int y) • { • } • and function body. • IntFindMax(int x, int y) • { • //body of the function…. • }
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.
http://gtu-mca.blogspot.com • The general form of calling stmt is: • Function_name (var1, var2,..); • Or • var_name=function name(var1, var2,..);
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.
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.
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 }
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; }
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.
#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);
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; • }
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
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>;
Types of storage classes • Automatic • External • Register • ststic
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
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.
//pgm1.c #include<stdio.h>] #include ”pgm2.c” Int I; Void show(); Int main() { i=10; Show(); Printf(“%d”,i); Return 0; }
//pgm2.c Extern int I; Show() { Printf(“%d”,i); }
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.
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.
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.
#include<stdio.h> Main() { Void show(); Printf(“\n first call”) Show(); Printf(“\n 2nd call”) Show(); Printf(“\n third call”) Show(); }
http://gtu-mca.blogspot.com Void show() { Static int i; Printf(“%d”,i); i++; } Op: First call i=0; 2nd call i=1 3rd call i=2
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.
#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 != ‘.’) • { • Print_backward(); • Printf(“%c”, ch); • } • } • i/p : hi o/p: ih
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………
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.
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.
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.
The purpose of base case • It terminates the condition. Without an explicitly defined base case, a recursive function would call itself indefinitely.
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)); • }
Long int factorial(int n) • { • If(n==0) • Return 1; • Else • Return (n * factorial(n-1)); • } • I/P: 3 • o/p: 6
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.
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.
GTU-MCA http://gtu-mca.blogspot.com