Java program to find product of digits

Hi programmers , welcome to new post of java programming. this post i’ll write various ways to perform product of digits using java language. Example of product of digits means digit multiplication of given number.
234 is solved as 2 * 3 * 4 = 24.
we can do product of digits of a number using while loop , for loop , do while loop or recursive function.

–product of digits of a number using while loop

using while loop

product of digits of a number using for loop

using for loop

— product of digits of a number using do while loop

using do-while loop

— product of digits of a number using recursive function

using recursion

Directly Test below codes into editor

--product of digits of a number using while loop
import java.util.*;
public class DW_DEV 
{
    public static void main(String[] args)
    {
        int n,mul=1,k;
        System.out.println("Enter the Numbers = ");
        Scanner sc= new Scanner(System.in);
        n=sc.nextInt();
        while(n!=0)
        {
            k = n%10;
            n = n/10;
            mul = mul*k;
        }
        System.out.println("Product of Digits of Number : "+mul);
    }
}


--product of digits of a number using for loop
import java.util.*;
public class DW_DEV 
{
    public static void main(String[] args)
    {
        int n,mul=1,k;
        System.out.println("Enter the Numbers = ");
        Scanner sc= new Scanner(System.in);
        n=sc.nextInt();
        for(; n >0;n = n / 10)
        {
            k = n%10;
            mul = mul*k;
        }
        System.out.println("Product of Digits of Number : "+mul);
    }
}


--product of digits of a number using do while loop
import java.util.*;
public class DW_DEV 
{
    public static void main(String[] args)
    {
        int n,mul=1,k;
        System.out.println("Enter the Numbers = ");
        Scanner sc= new Scanner(System.in);
        n=sc.nextInt();
        do
        {
            k = n %10;
            n = n/10;
            mul = mul*k;
        }while(n > 0);
        System.out.println("Product of Digits of Number : "+mul);
    }
}

--product of digits of a number using recursive function
import java.util.*;
public class DW_DEV {
    static int fun(int n){
        int mul = 1;
        if(n == 0)
            return 1;
        else {
            mul = mul*n%10;
            mul=mul*fun(n/10);
            return mul;
        }
    }
    public static void main(String[] args) {
        int num,k;
        System.out.println("Enter the Numbers = ");
        Scanner sc= new Scanner(System.in);
        num=sc.nextInt();
        k=fun(num);        
        System.out.println("Product of Digits of Number : "+k);
    }
}

Happy Coding…Thanks.

Post Author: adama