Back to Problem list
Back to Problem list
Problem 21:
Lets a function SOD(n) = sum of digits of n, so SOD(1123) = 1+1+2+3 = 7, SOD(15) = 16
Lets another function SSOD(n) = SOD(1) + SOD(2) + .... + SOD(n), given n , write a program to calculate SSOD(n)
Solution:
Not a hard problem at all. First we have to write a function to find SOD for a given n, and then we will write SSOD function.
#include<stdio.h>
int SOD(int n) { //this function returns the sum of the digits of n
int sum = 0;
while(n > 0) {
sum += n%10;
n /= 10;
}
return sum;
}
int SSOD(int n) {
int i, sum = 0;
for(i = 1; i<=n; i++) {
sum += SOD(i);
}
return sum;
}
int main() {
int n;
scanf("%d",&n);
printf("%d\n",SSOD(n));
return 0;
}
|
Back to Problem list