Here we’ll see how to write C program to reverse an integer. The reverse_integer() function takes an integer like 5234569 and returns 9654325.
#include <stdio.h> unsigned int reverse_integer(unsigned int in) { unsigned int out = 0; while(in) { out = out*10 + in%10; in /= 10; } return out; } int main(){ unsigned int in = 0; printf("Enter a positive integer: "); scanf("%d", &in); printf("Reverse integer: %d\n", reverse_integer(in)); return 0; }
Output:
Enter a positive integer: 5234569 Reverse integer: 9654325
Logic:
The reverse_integer() function takes the last digit of “in” by doing modulo operation by 10. For example, if in is 5234569, 5234569 % 10 would be the last digit 9. Then we are adding this digit at the end of “out”. To do that we need to multiply out with 10 and then add the digit. For the next iteration we are removing the last digit from “in” by doing div operation by 10. The loop continues for all digits of original “in”.
The post C Program to Reverse an Integer appeared first on QnA Plus.