I am looking for the c program for reverse the digits like ......
if i enter 123456
then the result would be .... 654321
plz any one help...
I am looking for the c program for reverse the digits like ......
if i enter 123456
then the result would be .... 654321
plz any one help...
Use % 10
to get the last digit. Output it. Divide the number by 10 to get all but the last digit. Use % 10
to get the last digit of that. And so on, until the number becomes 0.
Here is a simple solution to this complex problem:
#include <stdio.h>
int main()
{
int ch;
ch = getchar();
if (ch != '\n') {
main();
printf("%c", ch);
}
}
#include <stdio.h>
#include <stdlib.h>
static void newline(void)
{
printf("\n");
}
int main()
{
int ch;
ch = getchar();
if (ch != '\n') {
main();
printf("%c", ch);
} else {
atexit(newline);
}
}
strrev function reverses the string. If performance is not a problem then for instance you can do itoa, then strrev, then atoi. But the task is very simple even without strrev.
Here is another possibility. It is non-recursive, and perhaps a little less code. There is an example in the code comments to explain the logic.
/*
Example: input = 12345
The following table shows the value of input and x
at the end of iteration i (not in code) of while-loop.
----------------------
i | input | x
----------------------
0 12345 0
1 1234 5
2 123 54
3 12 543
4 1 5432
5 0 54321
----------------------
*/
uint32_t
reverseIntegerDigits( uint32_t input )
{
uint32_t x = 0;
while( input )
{
x = 10 * x + ( input % 10 );
input = input / 10;
}
return x;
}