Home » Sum of Digits in C without using a loop

Sum of Digits in C without using a loop

Learn about Sum of Digits in C without using a loop in the below code example. Also refer the comments in the code snippet to get a detailed view about what’s actually happening.

Contents

Sum of Digits in C without using a loop

Program:

 #include<stdio.h>
 int sumOfDigits(int n)
 {
   if(n==0) return 0;
   else return (n%10)+sumOfDigits(n/10);
 }
 int main()
 {
     int number, sum;

     printf("Enter any number: ");
     scanf("%d",&number);

     sum = sumOfDigits(number);

     printf("Sum of digits =  %d\n",sum);

     return 0;
 }

Output:

Enter any number: 123
Sum of digits = 6

Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.

Similar Codes :
Sum of Digits in C using the for loop
Sum of Digits in C using the while loop