Computer Science, asked by tongiaharsh22531, 1 month ago

Write a function in 'c' to calculate sum of digits of an integer.use this function in main

Answers

Answered by aashishkota
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 anindyaadhikari13
7

\texttt{\textsf{\large{\underline{Solution}:}}}

The given co‎‎de 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;

}

\texttt{\textsf{\large{\underline{Explanation}:}}}

  • The fu‎‎nction 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 fu‎‎nction is then called in main() so as to get the sum of digits of the number.

See the attachment for output.

Attachments:
Similar questions