0
Why this code not work
https://sololearn.com/compiler-playground/cC44kVmjS08y/?ref=app
1 Resposta
+ 2
The issue is here: c += b;
You never reset c to 0 inside the outer loop. So after the first iteration, c just keeps growing instead of starting fresh for the next digit-sum round. That makes the result incorrect. The correct code is:
int main() {
int a, b, c;
printf("Enter a number: ");
scanf("%d", &a);
while (a / 10 > 0) {
c = 0; // reset sum every round
while (a > 0) {
b = a % 10;
a = a / 10;
c += b;
}
a = c;
}
printf("Addition of digits till single digit is %d\n", a);
return 0;
}