Wednesday, 23 August 2017

Reverse of number using Recursion


This program reverse the number entered by the user and after that prints it on the screen. For instance, if a user enters 123 as input then 321 is printed as output.

C Program to reverse a number:

#include<stdio.h>
void main()
{
  int n,rem=0,rev=0;
  printf("Enter the number:");
  scanf("%d",&n");
  while(n>0)
  {
    rem=n%10;
    rev=rev*10+rem;
    n=n/10;
   }
 printf("Reverse of the number=%d",rev);
}


OUTPUT:

Enter the number:1234
Reverse of the number=4321

Using recursion:

#include<stdio.h>
void main()
{
  int n,rev;
  printf("Enter the number");
  scanf("%d",&n");
  rev=reverse(n);
  printf("Reverse of number=%d",rev);
}
int reverse(int num)
{
 int r=0,res=0;
 res=num%10;
 r=r*10+res;
 reverse(num/10);
 return(r);
 }

OUTPUT:

Enter the number:1234
Reverse of the number=4321

No comments:

Post a Comment