C Program to reverse digits of a number

In this blog post, we learn how to write a C Program to reverse the digits of a number? How to find reverse of any number using loop in C program. Logic to find the reverse of a number in C programming. How to write C program to reverse a number without using loop. How to write C program to reverse a number using array. How to write C program to reverse a number using function. Let’s see an example,

Input : num = 12345
Output : 54321


Input : num = 876
Output : 678

 

Algorithm to reverse number:

  1. Ask the user to enter any number.
  2. Declare and initialize another variable reversed with 0, where reversed an integer variable.
  3. Get the last digit of the given number by performing the modulo division (%) and store the value in last_digit variable, likey last_digit= number % 10.
  4. Multiply reversed by 10 and add last_digit, like reversed = reversed*10 + last_digit.
  5. Divide numbered by 10, like numbered/10.
  6. Repeat the steps 3 to 5 till numbered is not equal to (or greater than) zero.

 

Flow chart to find reverse a number:

 

flochart reverse a number

 

C Program to find reverse of a number:

 

#include <stdio.h>

int main()
{
    int number, reversed = 0;

    // Input a number from user
    printf("Enter any number = ");
    scanf("%d", &number);

    //Repeat the till number becomes 0
    while(number != 0)
    {
        /*
         * Increase place value of reversed and
         * add last digit to reversed
         */
        reversed = (reversed * 10) + (number % 10);

        // Remove last digit from number
        number /= 10;
    }

    printf("Reverse = %d", reversed);

    return 0;
}

Output;

Enter any number = 4562
Reverse = 2654

 

Code Explanation:

 

number = 4562
reversed = 0

reversed = reversed *10 + number %10 = 2
number = number/10 = 456

reversed = reversed *10 + number%10 = 20 + 6 = 26
number = number/10 = 45

reversed = reversed *10 + number%10 = 260 + 5 = 265
number = number/10 = 4

reversed = reversed *10 + number%10 = 265 + 4 = 2654
number = number/10 = 0

 

 

 

C Program to find reverse of a number using a function:

 

#include <stdio.h>


//function to reverse a number
int reversDigits(int number)
{
    int reversed = 0;
    while(number > 0)
    {
        reversed = reversed*10 + number%10;
        number = number/10;
    }
    return reversed;
}

int main()
{
    int number,reversed = 0;

    //Input a number from user
    printf("Enter any number = ");
    scanf("%d", &number);

    reversed = reversDigits(number);

    printf("Reverse = %d", reversed);

    return 0;
}

Output;

Enter any number = 1234
Reverse = 4321

 

Recommended Articles for you: