Perhaps the biggest reason for this to happen is probably that you are not assigning an initial value to num
, It’s already starting to get messy there because it depends on how lucky the memory is to have a useful value there. And more, after he does the calculation within the first loop of the for
the num
is not rebooted, so it takes the value that finished the previous step, which is certainly not the desired.
This happens because some people teach C from 30 years ago and not the current one, then those who learn fix the idea of declaring variables before and not near the use as it should be the most correct. Join this a better code organization makes it easier to see this kind of error. Even if you know that every variable should be initialized before use could still "eat ball" and not see by the lack of organization and by having the variable declaration much earlier than it needs it.
Initializing num
in all the implementation steps of the for
with the value of i
because it is the number that will be analyzed, works perfectly:
#include <stdio.h>
int main() {
for (int i = 10; i <= 500; i++) {
int inv = 0, num = i;
while (num != 0) {
inv = (inv * 10) + num % 10;
num /= 10;
}
if (i == inv) printf("%d ", i);
}
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
I’m not a fan because it’s less readable, but if you want to make it shorter:
#include <stdio.h>
int main() {
for (int i = 10; i <= 500; i++) {
int inv = 0, num = i;
do inv = (inv * 10) + num % 10;
while ((num /= 10) != 0);
if (i == inv) printf("%d ", i);
}
}