Friends, my goal is to find the numbers with odd sums from the numbers 1-99 in C language and print them on the screen. To try, I narrowed the scale and wrote 5 instead of 99 in the code. However, there is a problem, this code, which I think works very well in the logic in my head, enters an endless loop. I couldn’t find what to do. How do you think I fix this?
The expected output (think 5 instead of 99): "Sum of digits odd: 1 Sum of digits odd: 3"
int main() {
int n, m, result, temp;
for (int i = 1; i < 5; i++) {
temp = i;
while (i > 0) {
m = i % 10;
result += m;
i = i / 10;
}
if (result % 2 != 0) {
printf("%d", temp);
}
}
}
>Solution :
You use i++ in your loop, and yet use i = i / 10 in that loop antill i is 0. That means, that i gets stuck as 1.
You’ll either need another variable for the digit iteration, or to switch your use of i and temp so that i only gets changed by the loop’s incrementation:
int main()
{
int n, m, result, temp;
for(int i = 1; i < 5; i++)
{
result = 0;
temp = i;
while(temp>0)
{
m = temp % 10;
result += m;
temp = temp / 10;
}
if (result %2!=0)
{
printf("%d", i);
}
}
return 0;
}
Edit: I also missed that you forgot to initialize result with an initial value, so you basically keep adding to a garbage value. You should initialize it with 0 in each iteration.