Write a c program to find out sum of digit of given number





Code 1:
1. C program to add digits of a number
2. C program for sum of digits of a number
3. C program to calculate sum of digits

#include<stdio.h>
int main(){
  int num,sum=0,r;
  printf("Enter a number: ");
  scanf("%d",&num);
  while(num){
      r=num%10;
      num=num/10;
      sum=sum+r;
  }
  printf("Sum of digits of number:  %d",sum);
  return 0;
}

Sample output:
Enter a number: 123
Sum of digits of number:  6

Code 2:
1. 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

Code 3:
1. Sum of digits in c using recursion

#include<stdio.h>

int getSum(int);
int main(){
  int num,sum;
  printf("Enter a number: ");
  scanf("%d",&num);

  sum = getSum(num);

  printf("Sum of digits of number:  %d",sum);
  return 0;
}

int getSum(int num){

    static int sum =0,r;

    if(num!=0){
      r=num%10;
      sum=sum+r;
      getSum(num/10);
    }

    return sum;
}

Sample output:
Enter a number: 45
Sum of digits of number:  9






12 comments:

  1. Replies
    1. EXCELLENT PROGRAMINGWITH ANSWERS
      IT'S LOT OF
      HELP YOU

      Delete
  2. thanx dude

    ReplyDelete
  3. please tell me how to write a programme to generate Fibonacci series using recursion

    ReplyDelete
  4. Sir, Plz tell me When there is the requirement to see the numbers from 1 to 2000 using for...loop it displays one screen i want to see it using pagewise. what is the procedure.

    Kamala kanta Rath

    ReplyDelete
  5. cool but each information is necessary to us so upload every one programme//

    ReplyDelete
  6. explain me the logic

    ReplyDelete
  7. what is the use of while loop here?

    ReplyDelete
  8. Can any body tell me if i want to sum of a digit of a fraction no then what shal i hav to do?
    E.g 123456.789
    1+2+3+4+5+6+7+8+9=45

    ReplyDelete
  9. please tell me how to write c program to find second largest digit of given number using function

    ReplyDelete
  10. literally..a when ever i see his answers, i find myself nothing....his logic is too good..

    ReplyDelete
  11. Thanks a lots..its help me as a beginner on programming.

    ReplyDelete

Share It