DEV Community

Cover image for 100days code challenge
Darshan V ( Darshan Animus )
Darshan V ( Darshan Animus )

Posted on

100days code challenge

*Recursion
*

Recursion is the process in which the function call itself until some condition(the condition is called the base case) is reached.

the key points in recursion are:-

  • Recursive Function call.
  • Base case.

Base case :- it is stopping condition of the recursive call.

syntax :- static int fact(int n)
{
if(n==0)
return 1
return n*fact(n-1)
}

Example:- Palindrome check using Recursion
Palindrome is a number, which viewed from both sides is same.

import java.util.Scanner;

//Palindrome check with recursion
public class Palli {
    public int temp = 0;

    static int getReverse(int n, int temp) {
        if (n == 0)
            return temp;
        temp = temp * 10 + n % 10;
        return getReverse(n / 10, temp);
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n, temp = 0;
        System.out.println("Enter the Number");
        n = sc.nextInt();
        int cnum = getReverse(n, temp);
        System.out.println(cnum);
        if (n == cnum)
            System.out.println("The Number is a pallindrome");
        else
            System.out.println("The Number is not pallindrome");
    }
}
Enter fullscreen mode Exit fullscreen mode

Example 2:- Sum of Digits
The sum of digits is problem where a number is given and sum of each digit in the number must be calculated.
ex: 253 = 2+5+3 = 10

import java.util.Scanner;

public class SOD {
    static int soD(int n) {
        if (n == 0)
            return 0;
        return soD(n / 10) + n % 10;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        System.out.println(soD(n));
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)