Write a Java program to multiply two integers without using Operators and Loops


This Java program takes two integer inputs from the user and calculates their product using a recursive function multiple_numbera().

  • The function multiple_numbera() takes two integer arguments n1 and n2. It returns the product of these two numbers by recursively adding n1 to itself n2 number of times.
  • The base case for this recursive function is when n2 equals 0, in which case the product is 0.
  • If n2 is positive, then the function recursively adds n1 to the product of n1 and n2-1.
  • If n2 is negative, then the function recursively computes the product of n1 and -n2 and returns the negation of that product.
  • If none of these conditions are met, the function returns -1.
  • The main() function of the program prompts the user to input two integers using the Scanner class and then calls the multiple_numbera() function to compute their product.
  • Finally, the program prints the product of the two numbers.

Overall, this program recursively calculates the product of two integers entered by the user using the multiple_numbera() function.

Source Code

import java.util.*;
public class Multiple_TwoNumbers
{
	public static int multiple_numbera(int n1, int n2)
	{
		if (n2 == 0)
			return 0;      
		if (n2 > 0)
			return (n1 + multiple_numbera(n1, n2 - 1));            
		if (n2 < 0)
			return -multiple_numbera(n1, -n2);              
		return -1;
	} 
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		System.out.print("Enter the Number 1 : ");
		int n1 = input.nextInt();
		System.out.print("Enter the Number 2 : ");
		int n2 = input.nextInt();
		System.out.println("Multiply of Two Numbers : "+multiple_numbera(n1, n2));		
	}
 }

Output

Enter the Number 1 : 19
Enter the Number 2 : 31
Multiply of Two Numbers : 589

Example Programs