C Program Reverse Number by Recursion

By | March 9, 2020

C Program Reverse Number by Recursion

/* C Program Reverse Number By Recursion*/
#include <stdio.h>

/* function prototype */
long reverse(long);
 
/* main function  */
int main()
{
   long num, rev;
   
   printf("Enter a number to be reversed by Recursion: ");
   scanf("%ld", &num);
 
   rev = reverse(num);
 
   printf("Reverse Number = %ld\n", rev);
 
   return 0;
}

long reverse(long n) {

  
/* To preserve value of r variable 
during recursive calls, declare it static*/

   static long r = 0; 
   
   if (n == 0)
      return 0;
   
   r = r * 10;
   r = r + n % 10;
   reverse(n/10);
   return r;
}

 

Output
Enter a number to be reversed by Recursion: 456
Reverse Number = 654


/* To preserve value during recursive calls variblr r is declared as static. A static variable remains in memory while the program is running. A normal variable is destroyed when a function call where the variable was declared is ended. */

Leave a Reply

Your email address will not be published. Required fields are marked *