Recursion
Recursion
• Composing a function
• It is the process of specifying and establishing the user defined function by
specifying all of its elements and characteristic.
• Two parts
• header of the function
• body of the function
Header of the function:
return type function name( parameter list)
Body of the function
Consists of a set of statement enclosed within braces.
int add(int x,int y)
{
int z;
z=x+y;
return(z);
}
SYNTAX FOR FUNCTION DEFINITION
return type function_name(parameter list)
Parameter declaration
{
Local variable declaration;
.
.
Body of the function;
,
,return (expression)
}
Function Use/Function Call
• The function can be called by simple specifying the name of the
function,return value and parameter if present.
• Syntax
function_name();
function_name(parameters);
return value=functionname(parameters);
Ex:
Add()
Add(a,b)
C=add(a,b)
Function
Function prototype
No argument passing no input value
No argument passing return values
No argument passing return values
Program for argument passing
return value
#include<stdio.h> position=binsearch(list,key,low,high);
#include<conio.h> If(position==-1)
#include<stdlib.h> printf(“key not found”);
Int binsearch(int[],int,int,int); Else
void main() printt(‘key found at position %d”,position+1);
{ getch();
}
Int n,I,key,position;
int binsearch(int a[],int x,int first,int last)
Int low,high, list[20];
{
printf(‘enter the values of n”);
int middle;
for(i=0;i<n;i++)
If(first>last)
scanf(“%d”,&list[i]);
return -1;
printf(“enter the key element to be searched”); Middle=(first+last)/2;
scanf(“%d’,&key); If(x==a[middle])
low=0; return(middle);
high=n-1;
else if(x<a[middle])
binsearch(a,x,first,middle-1);
else
binsearch(a,x,middle+1,last);
}
Call by value
Swapping of two values
Call by reference
#include<stdio.h>
#include<conio.h>
#define PI 3.14
float sine(int x);
float cosine(int x);
float tangent(int x);
float logten(int x);
float squareroot(int x);
float exponent(int x);
float power(int x,int y);
void main()
{
int x,y,n;
float answer;
clrscr();
switch(n)
printf(“1.sin\n2.cos\n 3.tan\n {
4.log10\n 5.square root\n case 1: answer=sine(x);
6.exponent\n 7.power\n); printf(“%f”,answer);
break;
printf(“enter your choice\n”); case 2: answer=cosine(x);
scanf(“%d”,&n); printf(“%f”,answer);
break;
if(n<7&&n>0) case 3: answer=tangent(x);
{ printf(“%f”,answer);
break;
printf(“ enter the value of x”); case 4: answer=logten(x);
printf(“%f”,answer);
scanf(“%d”, &x); break;
scanf(“%d”, &y); case 5: answer=squareroot(x);
printf(“%f”,answer);
break;
case 6: exponent(x);
printf(“%f”,answer); float sine(int x)
break; {
default: return(sin(x*PI/180));
printf(“invalid choices”);
}
break;
getch(); float cosine(int x)
} {
float squareroot(int x) return(cos(x*PI/180));
{
}
return(sqrt(x));
}
float tangent(int x)
float exponent(int x) {
{ return(tan(x*PI/180));
return(exp(x)); }
}
float logten(int x)
float power(int x,int y)
{ {
return(pow(x,y)); return(log 10(x));
}
}