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

1

If I store the value '123' in an integer variable, how could I print the contents of the variable on the screen inverted?

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

    
asked by anonymous 14.10.2017 / 17:17

3 answers

3

You can use an integer-based solution, applying division and remainder of the division:

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 Ideone example

    
14.10.2017 / 17:30
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;
}
    
14.10.2017 / 17:28
1

To invert the integer, simply use the remainder and division of the integer, as follows:

#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
    
14.10.2017 / 17:37