Check The Programming Section
This problem can be solved using two different approach:
using iterative approach and
recursive approach
For example, if a number 1234 is given as input then sum of its digit is 1 + 2 + 3 + 4 = 10.
Iterative Approach
#include<stdio.h>
int sumOfDigits(int num){
int sum = 0;
while(num>0){
sum = sum + num%10;
num = num/10;
}
return sum;
}
int main(){
int num;
printf("Enter a number::");
scanf("%d",&num);
int sum = sumOfDigits(num);
printf("The sum of digits of %d is %d",num,sum);
return 0;
}
The Recursive Approach
#include<stdio.h>
int sumOfDigits(int num){
if(num>0){
return num%10 + sumOfDigits(num/10);
}
}
int main(){
int num;
printf("Enter a number::");
scanf("%d",&num);
int sum = sumOfDigits(num);
printf("The sum of digits of %d is %d",num,sum);
return 0;
}