Skip to main content

Posts

Showing posts with the label Recursion

Program for the power of the number using recursion in java

 Program for the power of the number using recursion in java Code: import java.util.Scanner; public class Test{ public static void main(String[] args) { Scanner scn = new Scanner(System.in); System.out.println(power(6,3)); } public static int power(int n,int pow){ if(pow==1){ return n; } return n * power(n,pow-1); } } or == import java.util.Scanner; public class Test{ public static void main(String[] args) { Scanner scn = new Scanner(System.in); System.out.println(power(2,10)); } public static int power(int n,int pow){ if(pow==1){ return n; } if(n==0){ return 0; } if(pow%2==0){ return power(n,pow/2) * power(n,pow/2); }else{ return power(n,pow/2) * power(n,pow/2) * n; } } }

program for printing the fibonacci series upto n using recursion in java

 program for printing the fibonacci series upto n using recursion in java Code:: import java.util.Scanner; public class Test{ static int a=0,b=1,c; public static void main(String[] args) { Scanner scn = new Scanner(System.in); System.out.println("Enter the number "); int n = scn.nextInt(); if(n==1){ System.out.println(0); }else if(n==2){ System.out.println(0+" "+1); }else{ System.out.print(0+" "+1+" "); fib(n-2); } } public static void fib(int n){ if(n==0){ System.out.println(); return; } c = a+b; a = b; b = c; System.out.print(c+" "); fib(n-1); } }

program for printing the 1 to n using recursion in java

 program for printing the 1 to n using recursion in java Code: import java.util.Scanner; public class Test{ public static void main(String[] args) { Scanner scn = new Scanner(System.in); int n = scn.nextInt(); print(n); } public static void print(int n){ if(n==0){ return; } print(n-1); System.out.println(n); } } i/p: 5 o/p: 1 2 3 4 5

program for the sum of n numbers using recursion in java

 program for the sum of n numbers using recursion in java Code: import java.util.Scanner; public class Test{ public static void main(String[] args) { Scanner scn = new Scanner(System.in); int n = scn.nextInt(); System.out.println(sum(n)); } public static int sum(int n){ if(n==0){ return 0; } return n + sum(n-1); } } i/p: 5 o/p: 15 i/p: 10 o/p: 55

Reverse a Stack using Recursion

 Reverse a Stack using Recursion Code:: import java.util.Stack; public class Test { public static void main(String[] args) { Stack<Integer> st = new Stack<Integer>(); st.add(1); st.add(2); st.add(3); st.add(4); System.out.println(st); reverse(st); System.out.println(st); } public static void reverse(Stack<Integer> s) { if(s.size()==0) { return; } int temp = s.pop(); reverse(s); insert(s,temp); } public static void insert(Stack<Integer> s,int temp) { if(s.size()==0) { s.push(temp); return; } int temp1 = s.pop(); insert(s,temp); s.push(temp1); } }