Partitioning the algorithm into functions

Asked

Viewed 83 times

1

The problem is this:

a function takes an int as parameter, and returns it written backwards and another to test whether the input number and the inverted number is palindromic or not.

I was able to solve the problem of identifying if the input number is palindromic, but I still have to divide the code into functions according to what was requested.

So far my code is like this:

int i, j;

scanf("%d", &i);

int n = i;
int l = 0;

while(n != 0){
    j = n % 10;
    l = (l * 10) + j;
    n = n / 10;
}

if(i == l)
    printf("sim");
else
    printf("nao");
  • And the code is not as you want ? What was missing ? The palindromo part works correctly. Just test with some numbers like 313, 123, 123321

  • not to be as I intended. what I have no difficulty with is splitting the code into function. for example: int inverts...

  • 1

    Choose a better name than l for your variable. In monospaced fonts (which we use to program) looks like the digit 1.

  • @Gabriel, has practice of using variables in this sequence,(regardless of the problem), i, j, l, m, n, o ..., but I comment on each one depending on the problem.

1 answer

3


I separated the user interaction part with the algorithm itself and made the communication through parameter and return.

#include <stdio.h>

int Inverte(int n) { //n é um parâmetro que recebe o que foi passado (digitado)
    int l = 0, j;
    while (n != 0) {
        j = n % 10;
        l = (l * 10) + j;
        n /= 10;
    }
    return l; //retorna o valor invertido que poderá ser usado onde precisa
}
int main(void) {
    int i;
    scanf("%d", &i);
    printf(i == Inverte(i) ? "sim" : "nao"); //em vez de comparar uma variável verifica com o retorno da função que é chamada com o que foi digitado como argumento
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • the return became much clearer now and what to pass to function Inverte.

Browser other questions tagged

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