Ans - Function in C: Q.13-Define The Function. and Explain With Example of Recursion
Ans - Function in C: Q.13-Define The Function. and Explain With Example of Recursion
Ans - Function in C: Q.13-Define The Function. and Explain With Example of Recursion
Ans - Function in C
Function are used for divide a large code into module, due to this we can easily
debug and maintain the code. For example if we write a calculator programs at that
time we can write every logic in a separate function (For addition sum(), for
subtraction sub()). Any function can be called many times.
Advantage of Function
Code Re-usability
Type of Function in C
Recursive Function in C
When Function is call within same function is called Recursion. The function which
call same function is called recursive function. In other word when a function call
itself then that function is called Recursive function.
Recursive function are very useful to solve many mathematical problems like to
calculate factorial of a number, generating Fibonacci series, etc.
Advantage of Recursion
Disadvantage of Recursion
#include<stdio.h>
#include<conio.h>
void main()
{
int fact(int);
int i,f,num;
clrscr();
printf("Enter any number: ");
scanf("%d",&num);
f=fact(num);
printf("Factorial: %d",f);
getch();
}
int fact(int n)
{
if(a<0)
return(-1);
if(a==0)
return(1);
else
{
return(n*fact(n-1));
}
}
Call by value
In call by value, original value can not be changed or modified. In call by value, when you
passed value to the function it is locally stored by the function parameter in stack memory
location. 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 such as main().
Call by value
#include<stdio.h>
#include<conio.h>
void main()
{
int a=100, b=200;
clrscr();
swap(a, b); // passing value to function
printf("\nValue of a: %d",a);
printf("\nValue of b: %d",b);
getch();
}
Call by 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
#include<stdio.h>
#include<conio.h>
void swap(int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
void main()
{
int a=100, b=200;
clrscr();
swap(&a, &b); // passing value to function
printf("\nValue of a: %d",a);
printf("\nValue of b: %d",b);
getch();
}