C Examples

C Program - Reverse digits of a given Integer



In C, the reverse of a given integer can be found out by using below mentioned methods.

Method 1: Using iteration

The method involves the following steps:

Input: MyNum
Step 1: Initialize the RevNum = 0
Step 2: Iterate over MyNum while it is greater than zero.
   Step 2a: Calculate remainder of MuNum / 10
   Step 2b: Update RevNum by RevNum * 10 + remainder
   Step 2c: Update MyNum by MyNum / 10
Step 3: Return RevNum

Example:

Input: 564

RevNum: 0
Iteration 1: 
    Remainder: 564 % 10 = 4
    RevNum: 0 * 10 + 4 = 4
    MyNum: 564 / 10 = 56

Iteration 2: 
    Remainder: 56 % 10 = 6
    RevNum: 4 * 10 + 6 = 46
    MyNum: 56 / 10 = 5

Iteration 3: 
    Remainder: 5 % 10 = 5
    RevNum: 46 * 10 + 5 = 465
    MyNum: 5 / 10 = 0

return RevNum = 465

The below block of code shows the implementation of above concept:

#include <stdio.h>
static int reverse(int); 

static int reverse(int MyNum){
  int RevNum = 0;
  int remainder;

  while(MyNum > 0){
    remainder = MyNum % 10;
    MyNum = MyNum / 10;
    RevNum = RevNum * 10 + remainder;
  }
  return RevNum;
}
int main() {
  int x = 1285;
  int y = 4567;
  printf("Reverse of %i is: %i\n", x, reverse(x));
  printf("Reverse of %i is: %i\n", y, reverse(y));
  return 0;
}

The above code will give the following output:

Reverse of 1285 is: 5821
Reverse of 4567 is: 7654

Method 2: Using Recursion

The above result can also be achieved using recursive function. Consider the example below:

#include <stdio.h>
static int reverse(int); 

static int reverse(int MyNum){
  static int RevNum = 0;
  static int base = 1;
  
  if(MyNum > 0){
    reverse(MyNum/10);
    RevNum += MyNum % 10 * base;
    base *= 10;
  }
  return RevNum;
}
int main() {
  int x = 7902;
  printf("Reverse of %i is: %i\n", x, reverse(x));
  return 0;
}

The above code will give the following output:

Reverse of 7902 is: 2097