How could I read a value of 3 digits and print them on the screen inversely in C?
If I stored the value '123' in a variable of the integer type, How could I print the contents of the variable on the screen inversely?
For example, for value '123 'the expected output would be' 321'; for' 472 'it would be'274'.
1
Author: Jefferson Quesado, 2017-10-14
3 answers
You can use an integer-based solution by applying division and division rest:
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
}
3
Author: Isac, 2017-10-14 15:30:20
Use 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;
}
1
Author: Rafael Coelho, 2017-10-14 15:28:34
To invert the integer, simply use the remainder and division of the integer, thus:
#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
1
Author: William Henrique, 2017-10-14 15:37:42