Sum of Digits Program in C

«
»

Sum of digits in a C program allows a user to enter any number, divide that number into individual numbers, and sum those individual numbers.

Example 1:

Given number = 14892 => 1 + 4 + 8 + 9 + 2 = 24.

Sum of digits of a given number “14892” is 24.

Example 2:

Given number = 3721 => 3 + 7 + 2 + 1 = 13.

Sum of digits of a given number “3721” is 13.

Note: Join free Sanfoundry classes at Telegram or Youtube
advertisement
advertisement
Problem Description

Write a C program to take the number from user and find the sum of its digits.

Problem Solution

Sum of Digits Algorithm in C:
1. Take the number as input.
2. Divide the number by 10 and store the remainder in a variable.
3. Add the remainder to the sum.
4. Repeat the process until the number is not 0.
5. Print the sum.

There are several ways to find the sum of digits in C language. Let’s take a detailed look at all the approaches for finding the sum of digits in C.

Take C Programming Practice Tests - Chapterwise!
Start the Test Now: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Method 1: Sum of Digits in C using While Loop (Naive Approach)

In this approach, we will divide the number by 10 and add the remainder to the sum.

Examples:
Input: 123 Output: 6

Input: 8679 Output: 30

Program/Source Code

Here is source code of the C program to compute the sum of digits in a given integer. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /* C program to find sum of digits of a number */
  2.  
  3. #include <stdio.h>
  4.  
  5. int main(void)
  6. {
  7.     int num, sum = 0, rem;
  8.     printf("Enter a number: ");
  9.     scanf("%d", &num);
  10.  
  11.     // Keep dividing until the number is not zero
  12.     while (num != 0)
  13.     {
  14.         rem = num % 10;
  15.         sum = sum + rem;
  16.         num = num / 10;
  17.     }
  18.     printf("Sum of digits of the number is %d", sum);
  19.     return 0;
  20. }
Program Explanation

1. Take an integer as a input and store it in the variable num.
2. Initialize the variable sum to zero.
3. Divide the input integer by 10 and obtain its remainder & quotient.
4. Store the remainder in the variable rem.
5. Increment the variable sum with variable rem.
6. Store the quotient into the variable num.
7. Repeats the process until the number is not 0.
8. Print the variable sum as output and exit.

advertisement

Time Complexity: O(n)
Time complexity of the above algorithm is O(n) as the while loop runs for log(n) times because at each iteration the number is divided by 10, where n is the number given as input.

Space Complexity: O(1)
In the above program, space complexity is O(1) as no extra variable is taken to store the value. All the variables initialized takes constant O(1) space.

Run Time Testcases

Testcase 1: In this case, we are entering the number “123” as input.

Enter a number: 123
Sum of digits of the number is 6

Testcase 2: In this case, we are entering the number “8679” as input.

advertisement
Enter a number: 8679
Sum of digits of the number is 30

Method 2: Sum of Digits in C using Recursive Approach

In this approach, we use a recursive function to calculate the sum of digits.

Methods used:
long sum_of_digits_recur(long num) – This function calculates the sum of digits of a number recursively.

Approach to Find the Sum of Digits using Recursion:
1. Take the number as input.
2. Call the function sum_of_digits_recur to calculate the sum of digits, the procedure is similar to whatever we did before with the difference that now it is recursive and therefore needs a few changes and a termination condition.
3. Print the sum.

Example:

Input: 3248162424
Output: 36

Input: 32471844421
Output: 40

Program/Source Code

Here is source code of the C program to find the sum of digits using recursion. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /* Find the sum of digits recursively */
  2.  
  3. #include <stdio.h>
  4.  
  5. long sum_of_digits_recur(long n)
  6. {
  7.     if (n == 0)
  8.         return 0;
  9.     else
  10.         return n % 10 + sum_of_digits_recur(n / 10);
  11. }
  12.  
  13. int main(void)
  14. {
  15.     long n;
  16.     printf("Enter a number: ");
  17.     scanf("%ld", &n);
  18.     printf("Sum of digits of the number is %ld", sum_of_digits_recur(n));
  19.     return 0;
  20. }
Program Explanation

1. Take an integer as a input and store it in the variable n.
2. Call the function sum_of_digits_recur to calculate the sum of digits.
3. Inside the function, we write a temrinating condition which is whenever the number becomes 0, the program should return back 0.
4. Otherwise, the program should add the remainder along with the number divided by 10 which is turn sent back to the function.
5. At the end, all sums are added up and the result is displayed to the user.

Time Complexity: O(n)
Time complexity of the above program is O(n), where n is the number given as input.

Space Complexity: O(n)
In the above program, space complexity is O(n).

Run Time Testcases

Testcase 1: In this case, we are entering the number “3248162424” as input.

Enter a number: 3248162424
Sum of digits of the number is 36

Testcase 2: In this case, we are entering the number “32471844421” as input.

Enter a number: 32471844421
Sum of digits of the number is 40

Method 3: Sum of Digits in C using Separate Function (Advanced Approach)

In this approach, we use a separate function to calculate the sum of digits.

Methods used:
long sum_of_digits(long num) – This function calculates the sum of digits of a number.

Approach:
1. Take the number as input.
2. Call the function sum_of_digits to calculate the sum of digits, the procedure is similar to whatever we did before.
3. Print the sum.

Examples:
Input: 14839481349
Output: 54

Input: 127381723
Output: 34

Program/Source Code

Here is source code of the C program to find the sum of digits using seperate function. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /* Find the sum of digits of a number using a separate function */
  2.  
  3. #include <stdio.h>
  4.  
  5. long sum_of_digits(long n)
  6. {
  7.     long sum = 0;
  8.     while (n > 0)
  9.     {
  10.         sum += n % 10;
  11.         n /= 10;
  12.     }
  13.     return sum;
  14. }
  15.  
  16. int main(void)
  17. {
  18.     long n;
  19.     printf("Enter a number: ");
  20.     scanf("%ld", &n);
  21.     printf("Sum of digits of the number is %ld", sum_of_digits(n));
  22.     return 0;
  23. }
Program Explanation

1. Take an integer as a input and store it in the variable n.
2. Call the function sum_of_digits_recur to calculate the sum of digits.
3. Inside the function, we write a temrinating condition which is whenever the number becomes 0, the program should return back 0.
4. Otherwise, the program should add the remainder along with the number divided by 10 which is turn sent back to the function.
5. Finally, print the sum.

Suppose the user enters the number 14839481349. In the printf statement, we call the function sum_of_digits with the number 14839481349 as the argument. Inside the function, a while loop executes until the number is not 0. The loop adds the remainder to the sum.

Time Complexity: O(n)
Time complexity of the above program is O(n), where n is the number given as input.

Space Complexity: O(n)
In the above program, space complexity is O(1) as no extra variable is taken to store the value. All the variables initialized takes constant O(1) space.

Run Time Testcases

Testcase 1: In this case, we are entering the number “14839481349” as input.

Enter a number: 14839481349
Sum of digits of the number is 54

Testcase 2: In this case, we are entering the number “127381723” as input.

Enter a number: 127381723
Sum of digits of the number is 34

Method 4: Read a String and Find the Sum of all Digits in the String

This C program will find the sum of digits of a number taken as a string.

Methods used:
int sum(char*) – This function will find the sum of digits of the string.

Approach:
1. Take the string as input.
2. Store the string in a variable.
3. Inside for loop, take the string and extract every character and while finding its value as a digit, add it to the sum.
4. If the character is not a digit, then we ignore it.
5. If the character is a digit, then we add it to the sum.
6. Return the sum.
7. Print the sum.

Examples:

Input: 82346y8d83 Output: 32

Input: de29382h Output: 24

Program/Source Code

Here is source code of the C program to find the sum of digits of a number taken as a string. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /* C program to find sum of digits of a number taken as a string */
  2.  
  3. #include <stdio.h>
  4. #include <string.h>
  5.  
  6. int sum(char *str)
  7. {
  8.     int sum = 0;
  9.     size_t i;
  10.     size_t l = strlen(str);
  11.     for (i = 0; i < l; i++) 
  12.     {
  13.         if (str[i] >= '0' && str[i] <= '9')
  14.         {
  15.             sum = sum + (str[i] - '0');
  16.         }
  17.     }
  18.     return sum;
  19. }
  20.  
  21. int main(void)
  22. {
  23.     char str[100];
  24.     printf("Enter the string: ");
  25.     scanf("%s", str);
  26.     printf("The sum of digits of numbers in the string is: %d", sum(str));
  27.     return 0;
  28. }
Program Explanation

1. The program begins with asking the user to enter the string.
2. The string is stored in a variable str and then passed to the function sum().
3. In the function sum(), we begin with initializing the variable sum to 0.
4. Then extract every character from the string and while finding its value as a digit, add it to the sum.
5. If the character is not a digit, then ignore it. If the character is a digit, then add it to the sum and finally return the sum.

Run Time Testcases

Testcase 1: In this case, we are entering the number “82346y8d83” as input.

Enter a number: 82346y8d83
Sum of digits of the number is 32

Testcase 2: In this case, we are entering the number “de29382h” as input.

Enter a number: de29382h
Sum of digits of the number is 24

To practice programs on every topic in C, please visit “Programming Examples in C”, “Data Structures in C” and “Algorithms in C”.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.