Sum of digits using recursion function in java. The source code for a Java program that uses recursion to find the sum of a number’s digits. As an input, you can use any decimal number. Now we feed that number to a new function, where we utilize the modulo operator and recursion to determine the sum of digits as output.

import java.util.Scanner;

public class Main

{

int sum = 0;

public static void main(String[] args)

{

int n;

Scanner s = new Scanner(System.in);

System.out.print("Enter the numbers");

n = s.nextInt();

Main obj = new Main();

int a = obj.add(n);

System.out.println("Sum"+a);

}

int add(int n)

{

sum = n % 10;

if(n == 0)

{

return 0;

}

else

{

return sum + add(n / 10);

}

}

}

Output:

Enter the number:45

Sum:9

## Recursion Function in Java

In computer science, recursion is a phenomena that is utilized to solve large problems by breaking them down into smaller ones. Recursion is the process through which a function directly or indirectly invokes itself.

Recursive function is the name given to the related function. Reduce the number of times a function is called unnecessarily. Recursion allows one to solve issues quickly, whereas the iterative solution is large and complex.

A recursive function is one that calls itself while it is being executed. The process may be repeated numerous times, with each iteration ending with the output of the result. Programmers can use recursive functions to develop efficient programs with a small amount of code.

## Purpose of Recursion Function in Java

Recursion is a problem- solving technique in which the solution is based on the solutions to smaller instances of the same problem. Iteration can usually handle such problems, but it requires identifying and indexing the smaller instances at programming time.