C is very powerful language and mother of many language. If you learn C and C++ you can strong you base. In programming If your base is strong you can build anything.

How to Reverse Integer in C Language?

Lets take a example if we have 321 integer and we want it in reverse order. It should be print 123.

We will need a function so we can reuse it. We can call it reverseOrder or something that sound slimier to their work.

How to Slice String in C Language?

reverseOrder Function

It should return integer after the process.

CCopy
static int reverseOrder(int x)
{
    int y = 0;
    while (x != 0) {
        int n = x % 10;
        if (y > INT_MAX / 10 || y < INT_MIN / 10) {
            return 0;
        }
        y = y * 10 + n;
        x /= 10;
    }
    return y;
}

Its a simple function that process the integer and make it reverse.

Now let we execute it main.

CCopy
int main(void)
{
    int x = 123;
    printf("Original integer: %12d",x);
    printf("\nReverse integer : %12d",reverseOrder(x));
    return 0;
}

Whole File

CCopy
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

static int reverseOrder(int x)
{
    int y = 0;
    while (x != 0) {
        int n = x % 10;
        if (y > INT_MAX / 10 || y < INT_MIN / 10) {
            return 0;
        }
        y = y * 10 + n;
        x /= 10;
    }
    return y;
}
int main(void)
{
    int x = 123;
    printf("Original integer: %12d",x);
    printf("\nReverse integer : %12d",reverseOrder(x));
    return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *