Product of digits in a number

This program is closely similar to this one: Count number of digits in a given integer. The only difference here is instead of counting the total number of digits we are multiplying each digit by another one until the user given number becomes 0 or less than 0.

Logic

First of all, we are declaring one variable product with value 1, we are going to use this variable to store the product of all digits, now after taking input from the user, inside the while loop, we have to extract each digit by performing modulo operation.

The modulo operation returns the remainder after dividing a number by another number. If we perform modulo operation with 10 on any number it will return the last most digit, we have to multiply and store the result into the variable product.

After that remove the last most digit from the number and perform the same again until the number becomes 0 or less than 0. Once the loop is completed simple print the variable product containing the product of all digit.

Program

import java.util.Scanner;

public class DigitProduct {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int num, temp;
        int product = 1;

        // Take input from user
        System.out.print("Enter any number : ");
        num = scanner.nextInt();

        temp = num;

        while(temp != 0) {

            product = product * (temp % 10);

            // Remove last digit from temp.
            temp = temp / 10;
        }

        System.out.println("\nProduct of all digits in " + num + " : " + product);
    }

}

Output

Enter any number : 123456
Product of all digits in 123456 : 720