Site icon Study Algorithms

Write a C program to reverse digits of a number?

ITERATIVE VERSION

The iterative version can be done in this way:-

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;
}
Exit mobile version