Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Recursion
  • Practice Recursion
  • MCQs on Recursion
  • Recursion Tutorial
  • Recursive Function
  • Recursion vs Iteration
  • Types of Recursions
  • Tail Recursion
  • Josephus Problem
  • Tower of Hanoi
  • Check Palindrome
Open In App
Next Article:
Find sum of digits in factorial of a number
Next article icon

Sum of Digits of a Number

Last Updated : 07 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given a number n, find the sum of its digits.

Examples : 

Input: n = 687
Output: 21
Explanation: The sum of its digits are: 6 + 8 + 7 = 21

Input: n = 12
Output: 3
Explanation: The sum of its digits are: 1 + 2 = 3

Table of Content

  • Iterative Approach
  • Recursive Approach
  • Taking Input Number as String

Iterative Approach

The idea is to add the digits starting from the rightmost (least significant) digit and moving towards the leftmost (most significant) digit. This can be done by repeatedly extracting the last digit from the number using modulo 10 operation, adding it to the sum, and then removing it using integer division by 10. For eg: n = 1567, then 1567 / 10 = 156.7 = 156(Integer Division).

C++
// Iterative C++ Code to find sum of digits  #include <iostream> using namespace std;  int sumOfDigits(int n) {     int sum = 0;     while (n != 0) {          // Extract the last digit         int last = n % 10;          // Add last digit to sum         sum += last;          // Remove the last digit         n /= 10;     }     return sum; }  int main() {     int n = 12345;     cout << sumOfDigits(n);     return 0; } 
C
// Iterative C Code to find sum of digits  int sumOfDigits(int n) {     int sum = 0;     while (n != 0) {          // Extract the last digit         int last = n % 10;          // Add last digit to sum         sum += last;          // Remove the last digit         n /= 10;     }     return sum; }  int main() {     int n = 12345;     printf("%d", sumOfDigits(n));     return 0; } 
Java
// Iterative Java Code to find sum of digits  class GfG {     static int sumOfDigits(int n) {         int sum = 0;         while (n != 0) {              // Extract the last digit             int last = n % 10;              // Add last digit to sum             sum += last;              // Remove the last digit             n /= 10;         }         return sum;     }      public static void main(String[] args) {         int n = 12345;         System.out.println(sumOfDigits(n));     } } 
Python
# Iterative Python Code to find sum of digits  def sumOfDigits(n):     sum = 0     while n != 0:          # Extract the last digit         last = n % 10          # Add last digit to sum         sum += last          # Remove the last digit         n //= 10     return sum  if __name__ == "__main__": 	n = 12345 	print(sumOfDigits(n)) 
C#
// Iterative C# Code to find sum of digits  using System; class GfG {     static int sumOfDigits(int n) {         int sum = 0;         while (n != 0) {              // Extract the last digit             int last = n % 10;              // Add last digit to sum             sum += last;              // Remove the last digit             n /= 10;         }         return sum;     }      static void Main() {         int n = 12345;         Console.WriteLine(sumOfDigits(n));     } } 
JavaScript
// Iterative JavaScript Code to find sum of digits  function sumOfDigits(n) {     let sum = 0;     while (n !== 0) {          // Extract the last digit         let last = n % 10;          // Add last digit to sum         sum += last;          // Remove the last digit         n = Math.floor(n / 10);     }     return sum; }  // Driver Code let n = 12345; console.log(sumOfDigits(n)); 

Output
15

Time Complexity: O(log10n), as we are iterating over all the digits.
Auxiliary Space: O(1)

Recursive Approach

We can also use recursion to find the sum of digits. The idea is to extract the last digit. add it to the sum, and recursively call the function with the remaining number (after removing the last digit).

  • Base Case: If the number is 0, return 0.
  • Recursive Case: Extract the last digit and add it to the result of recursive call with n / 10.
C++
// Recursive C++ Code to find sum of digits  #include <iostream> using namespace std;  int sumOfDigits(int n) {          // Base Case     if (n == 0)         return 0;      // Recursive Case     return (n % 10) + sumOfDigits(n / 10); }  int main() {     cout << sumOfDigits(12345);     return 0; } 
C
// Recursive C Code to find sum of digits  #include <stdio.h> int sumOfDigits(int n) {          // Base Case      if (n == 0)         return 0;      // Recursive Case     return (n % 10) + sumOfDigits(n / 10); }  int main() {     printf("%d", sumOfDigits(12345));     return 0; } 
Java
// Recursive Java Code to find sum of digits  import java.io.*;  class GfG {     static int sumOfDigits(int n) {                  // Base Case         if (n == 0)             return 0;          // Recursive Case         return (n % 10) + sumOfDigits(n / 10);     }      public static void main(String[] args) {         System.out.println(sumOfDigits(12345));     } } 
Python
# Recursive Python Code to find sum of digits  def sumOfDigits(n):          # Base Case     if n == 0:         return 0        # Recursive Case     return n % 10 + sumOfDigits(n // 10)   if __name__ == "__main__":     print(sumOfDigits(12345)) 
C#
// Recursive C# Code to find sum of digits  using System;  class GfG {     static int sumOfDigits(int n) {                  // Base Case         if(n == 0)             return 0;                // Recursive Case         return n % 10 + sumOfDigits(n / 10);     }      static void Main() {         Console.Write(sumOfDigits(12345));     } } 
JavaScript
// Recursive JavaScript Code to find sum of digits  function sumOfDigits(n) {          // Base Case     if (n == 0)         return 0;      // Recursive Case     return (n % 10) + sumOfDigits(Math.floor(n / 10)); }  // Driver code console.log(sumOfDigits(12345)); 

Output
15

Time Complexity: O(log10n), as we are iterating over all the digits.
Auxiliary Space: O(log10n) because of function call stack.

Taking Input Number as String

The idea is to take the input number as a string and then iterate over all the characters(digits) to find the sum of digits. To find the actual value of a digit from a character, subtract the ASCII value of ‘0’ from the character.

This approach is used when the input number is so large that it cannot be stored in integer data types.

C++
// C++ Code to find the sum of digits by // taking the input number as string  #include <iostream> using namespace std;  int sumOfDigits(string &s) {     int sum = 0;     for (int i = 0; i < s.length(); i++) {                // Extract digit from character         int digit = s[i] - '0';                // Add digit to the sum         sum = sum + digit;     }     return sum; }  int main() {     string s = "123456789123456789123422";      cout << sumOfDigits(s);     return 0; } 
C
// C Code to find the sum of digits by // taking the input number as string  #include <string.h> int sumOfDigits(char *s) {     int sum = 0;     for (int i = 0; i < strlen(s); i++) {                // Extract digit from character         int digit = s[i] - '0';                // Add digit to the sum         sum = sum + digit;     }     return sum; }  int main() {     char s[] = "123456789123456789123422";      printf("%d", sumOfDigits(s));     return 0; } 
Java
// Java Code to find the sum of digits by // taking the input number as string  class GfG {     static int sumOfDigits(String s) {         int sum = 0;         for (int i = 0; i < s.length(); i++) {                        // Extract digit from character             int digit = s.charAt(i) - '0';                        // Add digit to the sum             sum = sum + digit;         }         return sum;     }      public static void main(String[] args) {         String s = "123456789123456789123422";         System.out.println(sumOfDigits(s));     } } 
Python
# Python Code to find the sum of digits by # taking the input number as string  def sumOfDigits(s):     sum = 0     for i in range(len(s)):                # Extract digit from character         digit = ord(s[i]) - ord('0')                 # Add digit to the sum         sum = sum + digit     return sum  if __name__ == "__main__":     s = "123456789123456789123422"     print(sumOfDigits(s)) 
C#
// C# Code to find the sum of digits by // taking the input number as string  using System;  class GfG {     static int sumOfDigits(string s) {         int sum = 0;         for (int i = 0; i < s.Length; i++) {                        // Extract digit from character             int digit = s[i] - '0';                        // Add digit to the sum             sum = sum + digit;         }         return sum;     }      static void Main() {         string s = "123456789123456789123422";          Console.WriteLine(sumOfDigits(s));     } } 
JavaScript
// JavaScript Code to find the sum of digits by // taking the input number as string  function sumOfDigits(s) {     let sum = 0;     for (let i = 0; i < s.length; i++) {                // Extract digit from character         let digit = s[i] - '0';                // Add digit to the sum         sum = sum + digit;     }     return sum; }  // Driver Code let s = "123456789123456789123422"; console.log(sumOfDigits(s)); 

Output
104

Time Complexity: O(len(s)), as we are iterating over all the characters(digits).
Auxiliary Space: O(1)



Next Article
Find sum of digits in factorial of a number
author
kartik
Improve
Article Tags :
  • DSA
  • Recursion
  • cpp-puzzle
  • number-digits
Practice Tags :
  • Recursion

Similar Reads

  • Sum of digit of a number using recursion
    Given a number, we need to find sum of its digits using recursion.Examples: Input: 12345Output: 15Explanation: Sum of digits → 1 + 2 + 3 + 4 + 5 = 15 Input: 45632Output: 20 Approach:To understand the algorithm, consider the number 12345 and refer to the illustration below.. Extract the last digit: 1
    3 min read
  • Find sum of digits in factorial of a number
    Given a number n, write code to find the sum of digits in the factorial of the number. Given n ≤ 5000 Examples: Input : 10 Output : 27 Input : 100 Output : 648 Recommended PracticeSum of digits in factorial of a numberTry It!It is not possible to store a number as large as 100! under some data types
    11 min read
  • Sum of all N digit palindrome numbers
    Given a number N. The task is to find the sum of all N-digit palindromes. Examples: Input: N = 2 Output: 495 Explanation: 11 + 22 + 33 + 44 + 55 + 66 + 77 + 88 + 99 = 495 Input: N = 7 Output: 49500000000 Naive Approach:Run a loop from 10^(n-1) to 10^(n) - 1 and check when the current number is palin
    7 min read
  • Sum of an array of large numbers
    Given an integer K and an array arr[] consisting of N large numbers in the form of strings, the task is to find the sum of all the large numbers of the array. Examples: Input: K = 50, arr[] = {“01234567890123456789012345678901234567890123456789”, “01234567890123456789012345678901234567890123456789”,
    10 min read
  • Sum of digits of a given number to a given power
    Given a number, we need to find the sum of all the digits of a number which we get after raising the number to a specified power.Examples: Input: number = 5, power = 4 Output: 13 Explanation: Raising 5 to the power 4 we get 625. Now adding all the digits = 6 + 2 + 5 Input: number = 9, power = 5 Outp
    4 min read
  • Spy Number (Sum and Products of Digits are same)
    A number is said to be a Spy number if the sum of all the digits is equal to the product of all digits. Examples : Input : 1412Output : Spy NumberExplanation : sum = (1 + 4 + 1 + 2) = 8product = (1 * 4 * 1 * 2) = 8since, sum == product == 8 Input : 132Output : Spy NumberExplanation : sum = (1 + 3 +
    4 min read
  • Check if the sum of digits of a number N divides it
    Given a number n, the task is to check if the sum of digits of the given number divides the number or not. Examples: Input : n = 12Output : YesExplanation: Sum of digits = 1+2 =3 and 3 divides 12. Input : n = 15Output : NoExplanation: Sum of digits = 1+5 =6 and 15 % 6 != 0. Using Iterative Method -
    6 min read
  • Recursive sum of digits of a number is prime or not
    Given a number n, we need to find the sum of each digits of the number till the number becomes a single digit. We need to print "yes" if the sum is a prime or "no" if it is not prime. Examples: Input : 5602 Output: No Explanation: Step 1- 5+6+0+2 = 13 Step 2- 1+3 = 4 4 is not prime Input : 56 Output
    5 min read
  • Sum of digits equal to a given number in PL/SQL
    Prerequisite - PL/SQL introduction In PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations. Given a number and range and the task is to display all
    2 min read
  • n-th number whose sum of digits is ten
    Given an integer value n, find out the n-th positive integer whose sum is 10. Examples: Input: n = 2 Output: 28 The first number with sum of digits as 10 is 19. Second number is 28. Input: 15 Output: 154 Method 1 (Simple): We traverse through all numbers. For every number, we find the sum of digits.
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences