Program to reverse a number in C using function

Here we are going to write a program to reverse a number in c using function. Reversing a number means suppose we have a number 5432 then its reverse will be 2345. To do c program to reverse a number we will follow the same approach that we followed in c program to find sum of digits i.e., by using modulo operator (%) we will extract the last digit of the number and by division operator (/) we will remove the last digit. Lets discuss about the algorithm.

Program to reverse a number in C using function

Algorithm-

1. Store last digit in dig = num%10

2. Create a variable rev and store reversed number in rev by using formula rev = (rev*10)+dig

3. Remove last digit by num = num/10

4. Repeat till num > 0

First we will create a function named rev() of int return type  and it will take one integer as parameter. The integer which we are sending as parameter is the number whose reverse we want find. Then at last in the function we will return the reverse of given number. Then in main() function we will call the rev() function, and store the returned value in a variable. And atlast print the reverse number. Now lets code it. But before going down I will suggest you to first try it on your own and then see the solution.

Program to reverse a number in C using function

#include <stdio.h>

int reverse(int n){
    int rev = 0, dig;

    while (n != 0)
    {
        dig = n % 10;
        rev = rev * 10 + dig;
        n = n/10;
    }

    return rev;
}

int main()
{

    int n, rev = 0, dig;

    printf("Enter an integer: ");
    scanf("%d", &n);

    printf("Reversed number = %d", reverse(n));
    return 0;
}


Output -

Enter an integer: 5421
Reversed number = 1245  


More like this-


• Armstrong Number Check using function

• Palindrome Number Check using function

• Perfect Number Check using function 

• Perfect Number Check

C programs list

Post a Comment

If you have any doubts, please let me know

Previous Post Next Post