Recursion :
A function can call itself, this is called recursion.
Recursion is the method of calling a function within its definition.
Recursion में function खुद हो call करता है
जैसे
main()
{
printf("This is the example of recursion");
main();
}
Recursion में function को हमेशा किसी Condition के साथ Call करना चाहिए अगर ऐसा नही करेगे तो Program Infinite Time के लिए चल जायेगा।
मान लीजिए अगर हमें Recursion का उपयोग करके Factorial calculate करना तो हो तो
0! = 1
1! = 1
2! = 2x1 = 2x1! = 2!2-1
NEXT : Array
PREVIOUS : User defined functions -III
A function can call itself, this is called recursion.
Recursion is the method of calling a function within its definition.
Recursion में function खुद हो call करता है
जैसे
main()
{
printf("This is the example of recursion");
main();
}
Recursion में function को हमेशा किसी Condition के साथ Call करना चाहिए अगर ऐसा नही करेगे तो Program Infinite Time के लिए चल जायेगा।
मान लीजिए अगर हमें Recursion का उपयोग करके Factorial calculate करना तो हो तो
0! = 1
1! = 1
2! = 2x1 = 2x1! = 2!2-1
/* Program to calculate factorial using recursion*/
#include<stdio.h>
#include<stdio.h>
#include<conio.h>
int factorial(int m);
int main(void)
{
int number, result;
clrscr();
printf("Enter a number");
scanf("%d", &number);
result = factorial(number);
printf("Number =%d Factorial =%d",number, result);
getch();
int factorial(int m);
int main(void)
{
int number, result;
clrscr();
printf("Enter a number");
scanf("%d", &number);
result = factorial(number);
printf("Number =%d Factorial =%d",number, result);
getch();
return 0;
}
int factorial(int m)
{
if(m==1|| m==0)
{
return 1;
}
else
{
return(m*factorial(m-1));
}
}
}
int factorial(int m)
{
if(m==1|| m==0)
{
return 1;
}
else
{
return(m*factorial(m-1));
}
}
Output :
Enter a number 3
Number =3 Factorial = 6
Number =3 Factorial = 6
/* Program base exponent using recursion*/
#include<stdio.h>
#include<stdio.h>
#include<conio.h>
int base_expo(int base, int exponent);
int main(void)
{
int b,e, result;
clrscr();
printf("Enter the base & exponent");
scanf("%d%d", &b,&e);
result = int base_expo(b,e);
printf("result =%d, result);
getch();
int base_expo(int base, int exponent);
int main(void)
{
int b,e, result;
clrscr();
printf("Enter the base & exponent");
scanf("%d%d", &b,&e);
result = int base_expo(b,e);
printf("result =%d, result);
getch();
return 0;
}
int base_expo(int base, int exponent)
{
if(exponent==1)
{
return (base);
}
else
{
return(base*base_expo(base, exponent-1));
}
}
}
int base_expo(int base, int exponent)
{
if(exponent==1)
{
return (base);
}
else
{
return(base*base_expo(base, exponent-1));
}
}
Output :
Enter the base & exponent 5 3
result = 125
result = 125
NEXT : Array
PREVIOUS : User defined functions -III
No comments:
Post a Comment