C

Reverse a Number in C using Recursive Function

In this tutorial, we are going to see how to reverse a number in C using recursive function. The following C program reverses the number entered by the user, and then displays the reversed number on the screen.

For example, if the user enters 123 as input, 321 is displayed as output. We use the modulo operator (%) in the program to get the digits of a number.

There are four ways to reverse a number in C, by using for loop, while loop, recursion, or by creating a function.
 

Reverse a Number in C using Recursive Function
#include <stdio.h>
 
int reversedNbr=0, remainder;

//Recursive function to reverse the given number
reverse(int nbr){
   if(nbr){
      remainder = nbr%10;
      reversedNbr = reversedNbr * 10 + remainder;
      reverse(nbr/10);
   }
   else
      return reversedNbr;
   return reversedNbr;
}

int main()
{
   int r, nbr;
 
   printf("Enter a number to reverse: ");
   scanf("%d", &nbr);
   
   r = reverse(nbr);
 
   printf("The reversed number is = %d\n", r);
 
   return 0;
}

Output:

Enter a number to reverse: 123
The reversed number is = 321

 

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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