Skip to main content

Practical-6

Write a Java Program to find the sum of the digits of given number.

Introduction

This Java program is used to sum the digits of a given number. It is a useful operation to understand the basic concepts of programming and to help in various coding tasks such as validation of Credit/Debit cards, IMEI numbers etc. This program can be used by anyone to learn basic Java programming.

Code

public class SumOfDigits
{
public static void main(String args[])
{
int num = 12345;
int sum = 0;

//use modulus operator to get sum of digits
while(num>0)
{
sum += num%10;
num = num/10;
}

System.out.println("Sum of digits of given number is "+sum);
}
}

Output

Sum of digits of given number is 15
Explanation

This program first takes a number as the input and assigns it to the num variable. We then set the sum variable to 0. The while loop is used to calculate the sum of the digits, since we want it to loop until all digits in the number are processed. Inside the loop, the modulus operator is used to get the last digit in the number each time the loop runs. We add the last digit of the number to the sum variable each time the loop runs and we divide the num variable by 10 to process the next digit. Once we are done processing all the digits, the while loop will exit and we will print the sum of the digits on the console.