I am looking for the C
program for reverse the digits like below:
If i enter:
123456
Then the result would
Looks like a very old thread. But I referred the solutions here and had to cook up my own solution after testing the different programs available as solution on this website. I realized that treating the number as int will not yield necessary reversing of digit if the number ends with zero(s). So I decided to treat the number as a string and then reverse the digits. This way, I get exact reverse of the digit from a string standpoint and not a mathematical one that discards zeros at the beginning of a number.
#include <stdio.h>
#include <string.h>
main()
{
char num[20];
int x=0,slen;
printf("Enter the number you want to reverse :");
scanf("%s",num);
slen=strlen(num);
char *pointertoarray = &num[slen];
for (x=slen;x>=0; x--){ printf("%c",*pointertoarray); pointertoarray--; }
printf("\n");
}
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.
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.
Read the number in a char array A
with scanf("%s", A)
or, better, with fgets and output the char array reversed by outputting each character starting from strlen(A) - 1
to 0
.
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;
}
use the power function.
while(count>=1)
{
var = num % 10;
sum = sum + var * pow(10, count - 1);
num =num / 10;
count--;
}