Prerequisite: Recursion in Java
In the previous article, we have discussed about Java Program to Check Armstrong Number by Using Recursion
In this program we are going to add two numbers by using recursion in Java programming language.
Java Program to Add Two Numbers by Using Recursion
Now let’s see different ways to add two numbers by using recursion.
Method-1: Java Program to Add Two Numbers By Using Static Input and Recursion
Approach:
- Declare and initialize two integer variables say
a
,b
- Declare another integer variable say
sum
to store the addition result. - Call a user defined method
add()
and passa
andb
as parameter. - Then inside the user defined method check if ‘b’ is equals to 0 then return ‘
a
‘ else return(1+add(a,b-1))
which will call the same method inside that user defined method. - Finally print the result.
Program:
class Main { public static void main(String args[]) { //Declare three integer variables int sum,a=1,b=3; System.out.println("Value for a: "+a); System.out.println("Value for b: "+b); sum=add(a,b); System.out.print("Sum of two numbers are: "+sum); } //Define the recursive method static int add(int a, int b) { if(b==0) return a; else return(1+add(a,b-1)); } }
Output: Value for a: 1 Value for b: 3 Sum of two numbers are: 4
Method-2: Java Program to Add Two Numbers By Using User Input and Recursion
Approach:
- Declare two integer variables say
a
,b
and take values input from user. - Declare another integer variable say
sum
to store the addition result. - Call a user defined method
add()
and passa
andb
as parameter. - Then inside the user defined method check if ‘b’ is equals to 0 then return ‘
a
‘ else return(1+add(a,b-1))
which will call the same method inside that user defined method. - Finally print the result.
Program:
import java.util.*; class Main { public static void main(String args[]) { //create the object of scanner class Scanner sc=new Scanner(System.in); System.out.print("Enter the value for a: "); //prompt the user to enter the value of a int a=sc.nextInt(); System.out.print("Enter the value for b: "); //prompt the user to enter the value of b int b=sc.nextInt(); //call the user defined method int sum=add(a,b); System.out.print("Sum of two numbers are: "+sum); } //Define the recursive method static int add(int a, int b) { if(b==0) return a; else return(1+add(a,b-1)); } }
Output: Enter the value for a: 4 Enter the value for b: 2 Sum of two numbers are: 6
Provided list of Simple Java Programs is specially designed for freshers and beginners to get familiarize with the concepts of Java programming language and become pro in coding.
Related Java Programs: