Sum of digits of a number in c using for loop






#include<stdio.h>
int main(){
  int num,sum=0,r;
  printf("Enter a number: ");
  scanf("%d",&num);

  for(;num!=0;num=num/10){
      r=num%10;
      sum=sum+r;
  }
  printf("Sum of digits of number:  %d",sum);
  return 0;
}

Sample output:
Enter a number: 567
Sum of digits of number:  18




No comments: