A recursive
method is a method that calls itself either directly or indirectly through
another method. A method call itself is
termed as Recursion.
Example: fact(n) = 1 ; if n=0
n*fact(n-1) ;
n ³
1
// Write a
program to print the factorial of a given number using recursion
class a
{
double fact(double x)
{
if(x==0)
return 1;
else
return x*fact(x-1);
}
}
class recur
{
public static void main(String[]
args)
{
a obj=new a();
int p=Integer.parseInt(args[0]);
double t=obj.fact(p);
System.out.println("facatorial="+t);
}
}
// Write a program to print
the first n Fibonacci sequence numbers using recursion
(Lab Program: 2)
class a
{
int
f(int x)
{
if(x==0||x==1)
return
x;
else
return
(f(x-1)+f(x-2));
}
}
class fibo
{
public
static void main(String[] args)
{
a
obj=new a();
int
p=Integer.parseInt(args[0]);
for(int
i=1;i<=p;i++)
{
int
t=obj.f(i);
System.out.println(" "+t);
}
}
}
// Write a program to print
the sum of ‘n’ numbers using the recursive formula
sum
(n) = 0 ; if
n = 0
n + sum(n-1) ; if n ³ 1
No comments:
Post a Comment