Write a function in 'c' to calculate sum of digits of an integer.use this function in main
Answers
Answered by
0
Answer:
#include<stdio.h>
int main()
{
int num,sum=0;
scanf("%d",&num);
while(num>0)
{
sum = sum + num%10;
num = num/10;
}
printf("%d",sum);
}
Answered by
7
The given code is written in C.
#include <stdio.h>
int sum_of_digits(int n){
if(n==0)
return n;
return n%10+sum_of_digits(n/10);
}
int main() {
int n;
printf("Enter a number: ");
scanf("%d",&n);
printf("Sum of digits in %d = %d",n,sum_of_digits(n));
return 0;
}
- The function sum_of_digits() calculates the sum of digits. Using recursion, we have calculated the sum of digits of a number.
- Then, a number is taken as input from the keyboard. The function is then called in main() so as to get the sum of digits of the number.
See the attachment for output.
Attachments:
Similar questions