C Example Code2026-03-202 min read
Calculate the sum of digits of an integer in C using loops and recursion. Step-by-step trace, edge cases, and code examples explained.
Problem Statement & Approach
Given an integer n, compute the sum of all its individual digits. For example, for $n = 4832$, the sum of digits is $4 + 8 + 3 + 2 = 17$.
Extraction Logic:
- Extract the last digit:
lastDigit = n % 10 - Add to sum:
sum += lastDigit - Remove the last digit:
n = n / 10 - Repeat until
n == 0.
C Code Implementation
c (ISO Standard)#include <stdio.h> #include <stdlib.h> int sumOfDigitsIterative(int n) { n = abs(n); /* Handle negative inputs */ int sum = 0; while (n > 0) { sum += n % 10; n /= 10; } return sum; } int sumOfDigitsRecursive(int n) { n = abs(n); if (n == 0) { return 0; } return (n % 10) + sumOfDigitsRecursive(n / 10); } int main() { int testValues[] = {4832, 9999, -512, 0, 7}; int len = sizeof(testValues) / sizeof(testValues[0]); for (int i = 0; i < len; i++) { int val = testValues[i]; printf("Sum of digits for %d:\n", val); printf(" Iterative: %d\n", sumOfDigitsIterative(val)); printf(" Recursive: %d\n\n", sumOfDigitsRecursive(val)); } return 0; }
Sample Output
text (ISO Standard)Sum of digits for 4832: Iterative: 17 Recursive: 17 Sum of digits for 9999: Iterative: 36 Recursive: 36 Sum of digits for -512: Iterative: 8 Recursive: 8
Complexity Analysis
- Time Complexity:
O(log₁₀ n)— We process each digit exactly once. - Space Complexity:
O(1)iterative,O(log₁₀ n)stack frames recursive.
Related Guides
- Check if digits read the same backwards in Palindrome Program in C.
- Master loops in C Programming Basics.