Java program to find sum of digits

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

— Sum of digits of a number using while loop

using while loop

–Sum of digits of a number using for loop

using for loop

–Sum of digits of a number using do while loop

using do while loop

–Sum of digits of a number using recursive function

using recursion

Directly Test below codes into editor

-- Sum of digits of a number using while loop
public class DW_DEV 
{
    public static void main(String[] args)
    {
        int n,sum=0,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;
            sum = sum + k;            
        }
        System.out.println("Sum of Digits of Number : "+sum);
    }
}

--Sum of digits of a number using for loop
import java.util.*;
public class DW_DEV 
{
    public static void main(String[] args)
    {
        int n,sum=0,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;
            sum = sum + k;
        }
        System.out.println("Sum of Digits of Number : "+sum);
    }
}

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

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

Happy Coding…Thanks.

Post Author: adama