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'.
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'.
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
}
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;
}
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