Capicua’s algorithm is not printed as it should

Asked

Viewed 126 times

0

Program to find all Capicua numbers (a number that is read in the same way backwards and forwards) between 10 and 500. I tried to do this but the figures are not being printed.

#include <stdio.h>

int main(){

    int i,num,inv,res;
    inv = 0;

    for(i=10;i<=500;i++){
        while(num != 0){
        res = num % 10;
        inv = (inv * 10) + res;
        num = num / 10;
    }
        if(i == inv)
            printf("%d ",i);
    }
    return 0;
}

1 answer

0


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);
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.