Question: Find sum of digits in a given number.
Input: 65536
Output: 25
Method 1 (Iterative):
In this code sample by using modulus operator(%), we extract the individual digits of given number then we add them together
#include<stdio.h> int findSum(int num) { int sum = 0, remainder; while(num != 0) { // This gives us the last digit remainder = num % 10; // Add the digit to the sum sum = sum + remainder; // This divides the number by 10 // and removes the last digit num = num / 10; } return sum; } int main(void) { printf("Enter an integer\n"); scanf("%d",&num); sum = findSum(num); printf("Sum of digits of given number = %d\n",sum); return 0; }
Method 2 (recursive):
#include <stdio.h> int findSumRecursive(int num) { // Making it static makes only one copy static int sum = 0; if (num == 0) { return 0; } sum = num%10 + findSumRecursive(num/10); return sum; } int main(void) { int num, sum; scanf("%d", &num); sum = findSumRecursive(num); printf("%d\n", sum); return 0; }