How could I read a 3-digit value and print them on the screen reversed in C?

Asked

Viewed 69 times

1

If I stored the '123' value in an integer type variable, how could I print the contents of the variable on the screen in reverse?

For example, for the value '123' the expected output would be '321'; for '472' it would be '274'.

  • I tried to leave the question more organized, so that others who go through the same problem can reach the answers. If you disagree with my editing, just undo it or edit the parts of disagreement

3 answers

3


You can use an integer-based solution by applying splitting and splitting:

int x = 123;

while (x > 0){ //enquanto tem digitos
    printf("%d", x % 10); //mostra o ultimo digito com resto da divisão por 10
    x = x /10; //corta o ultimo digito
}

See the example in Ideone

1

Use the sprintf function:

#include <stdio.h>

int main() {
    int someInt = 368;
    char str[3];
    sprintf(str, "%d", someInt);
    printf("%c%c%c", str[2], str[1], str[0]);
    return 0;
}
  • Your code will make an occasional mistake, str is using 4 characters in my accounts (3+ null-terminated digits)

1

To invert the integer, just use the rest and division of the integer, like this:

#include <stdio.h>
#include <stdlib.h>

int main(){

    int numero, numIvertido;

    printf("Digite um numero inteiro: ");
    scanf("%d",&numero);

    if(numero >= 0){
        do{
            numIvertido = numero % 10;
            printf("%d", numIvertido);
            numero /= 10;
        }while(numero != 0);
        printf("\n");
    }
    return 0;
}

Output:

Digite um numero inteiro: 1234567
7654321

Browser other questions tagged

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