Write a C Program to find the sum of digits of a number using recursion.
#include <stdio.h>
#include <string.h>
/* sum of digits of the given number */
void sumOfDigits(int num, int *sum) {
/* finds sum of digits */
if (num) {
*sum = *sum + num % 10;
/* recursive call */
sumOfDigits(num / 10, sum);
}
return;
}
int main() {
int num, sum = 0;
/* get the input value from the user */
printf("Enter your input value:");
scanf("%d", &num);
/* sum of digits of the given input */
sumOfDigits(num, &sum);
/* print the sum of digits of the given input */
printf("Sum of digits of %d is %d\n", num, sum);
return 0;
}
#include <string.h>
/* sum of digits of the given number */
void sumOfDigits(int num, int *sum) {
/* finds sum of digits */
if (num) {
*sum = *sum + num % 10;
/* recursive call */
sumOfDigits(num / 10, sum);
}
return;
}
int main() {
int num, sum = 0;
/* get the input value from the user */
printf("Enter your input value:");
scanf("%d", &num);
/* sum of digits of the given input */
sumOfDigits(num, &sum);
/* print the sum of digits of the given input */
printf("Sum of digits of %d is %d\n", num, sum);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter your input value:123456
Sum of digits of 123456 is 21
Enter your input value:123456
Sum of digits of 123456 is 21
No comments:
Post a Comment