C program to reverse the digits of a number in just three statements

  • Write a program in C to reverse the digits of a number in just three statements.
  • How to reverse the digits of a number using standard library functions.

Required knowledge : sprintf function, atoi function, strrev function.
Algorithm to reverse the digits of a number in just 3 statements
  • Convert the integer to a string using sprintf function.
  • Reverse the characters of the string using strrev function.
  • Convert string back to integer using atoi function.

C program to reverse the digits of a number in just three statements.

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
 
int main() {
   int number;
   char string[16];
 
   printf("Enter an integer\n");
   scanf("%d", &number);
   
   /* first convert integer to a string using sprintf function */
   sprintf(string, "%d", number);
   /* Reverse characters of string uisng strrev function */
   strrev(string);
   /* Convert string back to integer using atoi function */
   number = atoi(string);
 
   printf("Reversed Integer = %d", number);
 
   return 0;
}
Output
Enter an integer
1234
Reversed Integer = 4321