Checksum of a number is the sum of all its digits.
I wrote the following program to find the checksum of a number:
#include <stdio.h>
int read(){
int read;
printf("number between 1000 and 100.000: ");
scanf("%d", &read);
return read;
}
int calcSum(int num){
int a;
if (num < 10)
return num;
a = calcSum (num / 10) + num % 10;
if (a > 10)
a += calcSum (a / 10) + a % 10;
return a;
}
void output(int in, int num){
printf("checksum vof %d = %d", in, num);
}
int main(){
int num;
num = read();
output(num, calcSum(num));
return 0;
}
It works with some numbers like 11, 12 but not with numbers like 706
If a > 10
, you are performing the same operation multiple times. Just do:
int calcSum(int num) {
int a;
if (num < 10)
return num;
a = calcSum (num / 10) + num % 10;
return a;
}