1 public static int exponent(int n){
2 int ans;
3 if(n == 0)
4 return 1;
5 else if(n%2 == 0){
6 int k = exponent(n/2);
7 ans = k*k;
8 }
9 ans= 2 * exponent(n-1);
10
11 return ans ;
12 }
13
1class scratch{
2 public static long factorial(int n){
3 if ( n == 1 ){
4 return 1;
5 }
6 else{
7 return n * factorial( n - 1 );
8 }
9 }
10 public static void main(String[] args) {
11 System.out.println( factorial(5) );
12 //Print 120 (5!) to the console
13 }
14}
1// prints x number of $
2public static void recursion(int x) {
3 if(x == 0) { // base case
4 System.out.println();
5 } else { // recursive case
6 System.out.print("$");
7 recursion(x - 1);
8 }
9}
1Recursion is a basic programming technique
2you can use in Java, in which a method
3calls itself to solve some problem.
4 A method that uses this technique
5 is recursive. Many programming problems
6 can be solved only by recursion,
7and some problems that can be solved by
8other techniques are better solved by recursion.
9
10EXP-1: Factorial
11
12 public static long factorial(int n){
13 if (n == 1)
14 return 1;
15 else
16 return n * factorial(n-1);
17 }
18
19EXP-2: Fibonacci
20
21 static int n1=1, n2=2, n3=0;
22 public static void printFibo(int count){
23 if (count > 0) {
24 n3 = n1 + n2;
25 n1 = n2;
26 n2 = n3;
27 System.out.print(" " + n3);
28 printFibo(count-1);
29 }
30 }
1import java.util.Scanner;
2
3public class SumDigit {
4 public static void main(String[] argh){
5 System.out.println("Enter int");
6 Scanner input = new Scanner(System.in);
7 int n = input.nextInt();
8 int sum = 0 ;
9 int i = 0;
10 print( i =Sum_of_digits(sum,n));
11
12 }
13
14 public static int Sum_of_digits(int sum,int n){
15 if(n<=0)
16 return sum ;
17 sum += n%10;
18
19 return Sum_of_digits(sum,n/10);
20 }
21
22 public static void print(int n){
23 System.out.print(n);
24 }
25}
26
1public void removeDigits(String string) {
2 if(string.length == 1) {
3 if(Character.isDigit(string.CharAt(0))) {
4 return "";
5 } else {
6 return string;
7 }
8 } else {
9 if(Character.isDigit(string.CharAt(0))) {
10 return removeDigits(string.substring(1));
11 } else {
12 return string.substring(0, 1) + removeDigits(string.substring(1));
13
14public static void main(String[] args) {
15 String string = "1a2b3c"
16 System.out.println(removeDigits(string)); //will print "abc"
17}