Description
To find sum of digits of a number, extract digits one by one and add them. For extraction find modulus, add it to previous modulus and divide number by 10 in a loop until number become 0.
C/C++
/* C Program to find sum of digits of a number */ //Save it as SumDigits.c #include<stdio.h> int main(){ int number, sum=0, remainder; printf("Enter a number : "); scanf("%d",&number); while(number > 0){ remainder = number % 10; sum += remainder; number /= 10; } printf("The sum of digits : %d", sum); return 0; }
Input: Enter a number : 125 Output: The sum of digits : 8
Java
/* Java Program to find sum of digits of a number */ //Save it as SumDigits.java import java.io.*; import java.util.Scanner; public class SumDigits { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int number, sum=0, remainder; System.out.println("Enter a number : "); number = scanner.nextInt(); while(number > 0){ remainder = number % 10; sum += remainder; number /= 10; } System.out.println("The sum of digits : " + sum); } }
Input: Enter a number : 125 Output: The sum of digits : 8
Related Programs
1) Program to find sum of first and last digit of a number2) Program to find largest and smallest digit in a Number
3) Program to calculate Permutation And Combination
4) Program to reverse a number
5) Program to find largest and smallest character in a String
6) Program to calculate Volume and Surface Area of Sphere
7) Program To Check Armstrong Number
8) Program to Check Whether a Number is Prime or Not
9) Check whether a given number is a perfect number or not
10) Program to Check Leap Year