Home Misc Write a C program to reverse digits of a number?

Write a C program to reverse digits of a number?

by nikoo28
0 comment 2 minutes read

ITERATIVE VERSION

The iterative version can be done in this way:-

  • Input: num
  • Initialize rev_num = 0
  • Loop while num > 0
    • Multiply rev_num by 10 and add remainder of num
      divide by 10 to rev_num
      rev_num = rev_num*10 + num%10;
    • Divide num by 10
  • Return rev_num

Here is an implementation of the same.

#include

//Iterative function to reverse digits of num
int reverseDigits(int num)
{
    int rev_num = 0;
    while(num > 0)
    {
        rev_num = rev_num*10 + num%10;
        num = num/10;
    }
    return rev_num;
}

//Driver program to test the function
int main()
{
    int num = 4562;
    printf("Reverse of no. is %d", reverseDigits(num));
    return 0;
}

RECURSIVE WAY

#include

// Recursive function to reverse digits of num
int reverseDigits(int num)
{
  static int rev_num = 0;
  static int base_pos = 1;
  if(num > 0)
  {
    reverseDigits(num/10);
    rev_num  += (num%10)*base_pos;
    base_pos *= 10;
  }
  return rev_num;
}

// Driver program to test reverseDigits
int main()
{
    int num = 4562;
    printf("Reverse of no. is %d", reverseDigits(num));
    return 0;
}

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More