C program to Reverse an Integer Number/ Program for Reverse Number in C

This C program can reverse an integer. For example, this program reads 1234 and converts it into 4321.

Method: 1

In this method, first, we convert the integer variable into a string using sprintf() function. After that, we reverse that string using a revstr() function which we have defined. Finally, we convert the reversed string back into an integer using the atoi() function.

#include<stdio.h>
#include<stdlib.h>
#include <string.h>  
void revstr(char *str1)  
{  
    // declare variable  
    int i, len, temp;  
    len = strlen(str1); // use strlen() to get the length of str string  
      
    // use for loop to iterate the string   
    for (i = 0; i < len/2; i++)  
    {  
        // temp variable use to temporary ahold the string  
        temp = str1[i];  
        str1[i] = str1[len - i - 1];  
        str1[len - i - 1] = temp;  
    }  
}  
int main() {
   //const char *str = "12345";
   char str[4];
   int y = 1234; //atoi(str); // Using atoi()
   printf("\nThe value of y : %d", y);
   sprintf(str, "%d", y);
   printf("\nThe value of str : %s", str);
   revstr(str);
  printf("\nThe value of str after reversing : %s", str);
  y = atoi(str);
  printf("\nThe value of y after reversing : %d", y);
   return 0;
}

Output:


The value of y : 1234
The value of str : 1234
The value of str after reversing : 4321
The value of y after reversing : 4321

Method 2

In this method, we use a modulo operator to take a remainder and then construct a reverse number from these remainder numbers.

#include <stdio.h>
void reverse_int(int *num){
    
    int rev_num = 0;
    int digit;
    while (*num > 0) {
        digit = *num % 10; /*get digit*/
        rev_num = (rev_num * 10) + digit;
        *num = *num / 10;
    }
    
    *num = rev_num;
}
int main()
{
    int n = 1234; //input number to be reversed
    int dig, revNumber;
    reverse_int(&n);
    printf("Reverse Number is : %d\n", n);
    return 0;
}

Output:

Reverse Number is : 4321

Leave a Comment