C Program to calculate sum of digits of a number

Simple C Program to calculate sum of digits of a number.
#include<stdio.h>
int main()
{
 int n,sum=0;
 printf("Enter a number: ");
 scanf("%d",&n);
 while(n!=0)
 {
  int rem=n%10; //remainder
  sum=sum+rem;
  n=n/10;
 }
 printf("Sum of digits = %d\n",sum);
 return 0;
}
Another C program using for loop
#include<stdio.h>
int main()
{
 int n,sum=0;
 printf("Enter a number: ");
 scanf("%d",&n);
 for(;n!=0;)
 {
  int rem=n%10; //remainder
  sum=sum+rem;
  n=n/10;
 }
 printf("Sum of digits = %d\n",sum);
 return 0;
}
C program to calculate sum of digits using recursion
#include<stdio.h>
int SumOfDigits(int a)
{
 if(a==0)
 return 0;
 else
 return a%10+SumOfDigits(a/10);
}
int main()
{
 int n,sum;
 printf("Enter a number: ");
 scanf("%d",&n);
 sum=SumOfDigits(n);
 printf("Sum of digits = %d\n",sum);
 return 0;
}


Popular posts from this blog