C Program to find the reverse of a number

In this C Programming example, we will discuss the steps and implement the C program to reverse an input number using recursion and while loop.

1. Reversing a number

Reversing a number is a process where a number entered by the user is printed backward.

Example : 25836
Reverse Number : 63852

Helpful topics to understand this program better are-


2. C Program to Reverse a number using recursion

Let’s discuss the execution(kind of pseudocode) for the program to find the reverse of input number using recursion in C.

  1. We prompt the user to enter the value to reverse.
  2. Then we invoke the method rev_num(int revNumber), which recursively calls itself to find the reverse of the number.
  3. The global variable reverse is updated and control is returned to the main method and then finally the reversed value is printed on the console.

Let us implement this concept in the c program and find the reverse of an input number using recursion.

#include <stdio.h>

int reverse;
void rev_num(int number) {
  if (number > 0) {
    reverse = (reverse * 10) + (number % 10);
    rev_num(number / 10); // recursive call
  }
}

int main() {
  int num;
  printf("Enter a number:");
  scanf("%d", &num);
  rev_num(num);
  printf("Reverse Number is:%d\n", reverse);
  return 0;
}
Output
Enter a number:123456789
Reverse Number is:987654321

3. C Program to Reverse a number using while loop

Let’s now update the void rev_num(int number) method so that we can reverse a number using the while loop.

int reverse;
void rev_num(int number) {
  while (number > 0) {
    reverse = (reverse * 10) + (number % 10);
    number /= 10;
  }
}
Output
Enter a number:123456789
Reverse Number is:987654321

4. Conclusion

In this C Programming example, we have discussed how to find the reverse of an input number using recursion and while loop and discussed the execution of the program.


Helpful Links

Please follow C Programming tutorials or the menu in the sidebar for the complete tutorial series.

Also for the example C programs please refer to C Programming Examples.

All examples are hosted on Github.


Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! ?

Recommended -

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Index