Java Program to Find Product of Digits of a Number

In the previous article, we have seen Java Program to Find Sum of Digits of a Number

In this article we are going to see how to find product of digits of a number using Java programming language.

Java Program to Find Product of Digits of a Number

As we know dividing any number by 10, the remainder always gives the unit place digit. The number will be reduced to zero after we exhausted all its digits. We will use this theory to get our output.

Example:

528= 5*2*8 = 80
341= 3*4*1= 12
12= 1*2= 2
80451= 8*0*4*5*1 = 0

Let’s see different ways to find product of digits of a number.

Method-1: Java Program to Find Product of Digits of a Number By Using Modulo Operator and Number is Integer Value

Approach:

1. Create Scanner class object.
2. Ask user to enter the number.
3. Declare a variable product = 1 to store the sum of the digits.
4. Use the modulo operator to obtain the unit place digit and multiply it to product.

Program:

import java.util.Scanner;

public class Main
{
public static void main(String[] args)
{
// creating scanner class object
Scanner sc = new Scanner(System.in);
// taking input from user
System.out.print("Enter a number: ");
int n = sc.nextInt();
// calling method to find product of digits
int product = findProduct(n);
// printing product of digits
System.out.println("Product of each digit of the number: " + product);
}

//user defined method
//to find product of each digits of a number
private static int findProduct(int n)
{
// variable to store product
int product = 1;
while (n > 0) {
// extracting last digit and multiplying to sum
product *= n % 10;
n /= 10;
}
return product;
}
}

Output:

Enter a number: 12
Product of each digit of the number: 2

Method-2: Java Program to Find Product of Digits of a Number By Using Modulo Operator and Number is Numeric String Value

Approach:

1. Use the Integer.parseInt() method to covert the numeric string into an integer.
2. Declare a variable product=1 to store the product of the digits.
3. Use the modulo operator to obtain the unit place digit and multiply it to product.

Program:

public class Main
{
public static void main(String[] args)
{
String num = "345";

//calling method to find sum of digits
int sum = findProduct(num);
//printing product of digits
System.out.println("Product of each digit of the number: " + sum);
}

//user defined method
private static int findProduct(String num)
{
//convert numeric string into int type
int n = Integer.parseInt(num);
//variable to store product
int product = 1;
while (n > 0)
{
//extracting last digit and multiplying to product
product *= n % 10;
n /= 10;
}
return product;
}
}

Output:

Product of each digit of the number: 60

Grab the opportunity to learn all effective java programming language concepts from basic to advance levels by practicing these Java Program Examples with Output

Related Java Programs: