Program for Sum the digits of a given number

1.4

Given a number, find sum of its digits.

Example :

Input : n = 687
Output : 21

Input : n = 12
Output : 3

 
Below are the solutions to get sum of the digits.

1. Iterative:

C

// C program to compute sum of digits in 
// number.
# include<stdio.h>

/* Function to get sum of digits */
int getSum(int n)
{ 
   int sum = 0;
   while (n != 0)
   {
       sum = sum + n % 10;
       n = n/10;
   }
   return sum;
}

int main()
{
  int n = 687;
  printf(" %d ", getSum(n));
  return 0;
}

Java

// Java program to compute 
// sum of digits in number.
import java.io.*;

class GFG {
    
    /* Function to get sum of digits */
    static int getSum(int n)
    {    
        int sum = 0;
        
        while (n != 0)
        {
            sum = sum + n % 10;
            n = n/10;
        }
    
    return sum;
    }

    // Driver program
    public static void main(String[] args)
    {
        int n = 687;

        System.out.println(getSum(n));
    }
}

// This code is contributed by Gitanjali


Output :
21

How to compute in single line?
Below function has three lines instead of one line but it calculates sum in line. It can be made one line function if we pass pointer to sum.

C

# include<stdio.h>
/* Function to get sum of digits */
int getSum(int n)
{
    int sum;

    /* Single line that calculates sum */
    for (sum=0; n > 0; sum+=n%10,n/=10);

    return sum;
}

int main()
{
  int n = 687;
  printf(" %d ", getSum(n));
  return 0;
}

Java

// Java program to compute
// sum of digits in number.
import java.io.*;

class GFG {
    
    /* Function to get sum of digits */
    static int getSum(int n)
    {
        int sum;

        /* Single line that calculates sum */
        for (sum = 0; n > 0; sum += n % 10,
                                  n /= 10);

        return sum;
    }

    // Driver code
    public static void main(String[] args)
    {
        int n = 687;

        System.out.println(getSum(n));
    }
}

// This code is contributed by Gitanjali


Output :
21

2. Recursive
Thanks to ayesha for providing the below recursive solution.

C

int sumDigits(int no)
{
   return no == 0 ? 0 : no%10 + sumDigits(no/10) ;
}

int main(void)
{
    printf("%d", sumDigits(687));
    return 0;
}

Java

// Java program to compute
// sum of digits in number.
import java.io.*;

class GFG {
  
    /* Function to get sum of digits */ 
    static int sumDigits(int no)
    {
        return no == 0 ? 0 : no%10 + 
                  sumDigits(no/10) ;
    }

    // Driver code
    public static void main(String[] args)
    {
    int n = 687;

    System.out.println(sumDigits(n));
    }
}

// This code is contributed by Gitanjali


Output :
21

Please write comments if you find the above codes/algorithms incorrect, or find better ways to solve the same problem.

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:



1.4 Average Difficulty : 1.4/5.0
Based on 40 vote(s)