Java Programs

Please click on 1-2 Ads to keep this website's Study Material FREE and regularly Updated.

Program 11: Write a Java program to calculate the sum of the digits of a number.

Digit.java

import java.util.Scanner;

public class Digit
{
	// sumOfDigits() - A method to find the sum of the digits of a number
	static int sumOfDigits(int num)
	{
		int sum=0;
		int rem;
		
		while(num!=0)
		{
			rem=num%10;
			num=num/10;
			sum=sum+rem;
		}
		return sum;
	}

	//main method
	public static void main(String[] args) 
	{
		Scanner s =new Scanner(System.in);
		int n;
		
		System.out.println("Enter the number n");
		n=s.nextInt();
		
		//call to the method sumOfDigits().

		int sum1 = sumOfDigits(n);
		System.out.println(sum1);
	}
}



If you have any suggestion or found any error in the above program, then do let us know at [email protected] or just comment below.