Recursive Function is a functtion which calls itself.Every recursive function must have a base condition to stop the function else the program will never end
Advantage of Recurive Function
1.it makes the coding clean
2.it helps solve a complex problem by breaking it down into many parts
Question: Write a program to find the sum of a number from 1 to n using recursive function
Solution:
import java.util.Scanner;
public class Recursive1
{
static int sum=0;
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print("Enter A number:");
int n = s.nextInt();
System.out.print("The sum of the numbers from 1 to " + n +" is " + sum(n));
}
public static int sum(int n)
{
int i=n;
if(i!= 0)
{
sum = sum + i;
i--;
return sum(i);
}
return(sum);
}
}
Output:
Question: Write a program to find the factorial of a given number using recursive function
Solution:
import java.util.Scanner;
public class Recursive2
{
static int fac=1;
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print("Enter A number:");
int n = s.nextInt();
System.out.print("The factorial of the number is " + n +" is " + fac(n));
}
public static int fac(int n)
{
int i=n;
if(i!= 0)
{
fac = fac * i;
i--;
return fac(i);
}
return(fac);
}
}
output:
Question:Write a program to print multiplication table of any number from 1 to 12 using recursive function
Solution:
import java.util.Scanner;
public class Recursive3
{
static int i=1;
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print("Enter A number:");
int n = s.nextInt();
System.out.print("The Multiplication table of " + n +" from 1 to 12 is \n");
mut(n);
}
public static int mut(int n)
{
if(i<=12)
{
System.out.println(i +"*"+ n+ " : " + (i*n));
i++;
fac(n);
}
return(n);
}
}
output:
Question: Write a program to find the prime number using recursive program
Solution
import java.util.Scanner;
public class Recursive4
{
static int count=0;
static int i=1;
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print("Enter a number:");
int n = s.nextInt();
System.out.print("The given number "+ n +" ");
check(n);
if(count==2)
System.out.print("is prime");
else
System.out.print("is not prime");
}
public static int check(int n)
{
if(i<=n)
{
if(n%i==0)
{
count++;
}
i++;
return check(n);
}
return count;
}
}
Output:
Question: Write a program to find the cube of a given number
Solution:
import java.util.Scanner;
public class Recursive5
{
static int i =1;
static int p =1;
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print("Enter a number:");
int n = s.nextInt();
System.out.print("The cube of " + n+ " is " + cal(n));
}
public static int cal(int n)
{
if(i&jlt;=3)
{
p=p*n;
i++;
return cal(n);
}
return p;
}
}
output:
0 Comments:
Post a Comment