Created
May 10, 2021 07:43
-
-
Save jagdish4501/2203b61eec990dc9e36942acde376c06 to your computer and use it in GitHub Desktop.
Let us c Q .A 5-digit positive integer is entered through the keyboard, write a function to calculate sum of digits of the any-digit number: (1) Without using recursion (2) Using recursion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*using recursion */ | |
#include <stdio.h> | |
int digitsum(int ); | |
int main() | |
{ | |
int num, sum; | |
printf("Enter a number "); | |
scanf("%d", &num); | |
sum = digitsum(num); | |
printf("sum of digit %d", sum); | |
} | |
int digitsum(int num) | |
{ | |
if(num<10) | |
{ | |
return num; | |
}else | |
return (num%10)+digitsum(num/10); | |
} | |
/* other methode 1*/ | |
/* using function*/ | |
#include <stdio.h> | |
int digitsum(int); | |
int main() | |
{ | |
int num, sum; | |
printf(" Enter number :"); | |
scanf("%d", &num); | |
sum = digitsum(num); | |
printf(" sum of digit %d", sum); | |
} | |
int digitsum(int num) | |
{ | |
int sum = 0; | |
for (int i = 1; num > 0; i++) | |
{ | |
int temp = num % 10; | |
sum = sum + temp; | |
num = num / 10; | |
} | |
return sum; | |
} | |
/*other methode 2*/ | |
/**using pointer */ | |
#include <stdio.h> | |
void digitsum(int *, int *); | |
int main() | |
{ | |
int num, sum = 0; | |
printf(" Enter number :"); | |
scanf("%d", &num); | |
digitsum(&num, &sum); | |
printf(" sum of digit %d", sum); | |
} | |
void digitsum(int *num, int *sum) | |
{ | |
for (int i = 1; *num > 0; i++) | |
{ | |
int temp = *num % 10; | |
*sum = *sum + temp; | |
*num = *num / 10; | |
} | |
} | |
/* other method */ | |
/* simple program */ | |
#include <stdio.h> | |
int main() | |
{ | |
int num, sum = 0; | |
printf(" Enter number :"); | |
scanf("%d", &num); | |
for (int i = 1; num > 0; i++) | |
{ | |
int temp = num % 10; | |
sum = sum + temp; | |
num = num / 10; | |
} | |
printf(" sum of digit %d", sum); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment