C Program to Reverse a Number Using Function

Previously we have written a C program to find the reverse of a given number, but now we will develop the same using the C function. Write a C program to reverse a number using a function. Example, the reverse of number 123856 is 658321.

A function is a block of code that performs a specific task. For example, the main is a function and every program execution starts from the main function in C programming. The function is a small program that is used to do a particular task. In C a big program divided into several small subroutines/functions/procedures. Hence C is a function-oriented programming language.

The C program is made of one or more pre-defined/user-defined functions. Every program must have at least one function with the name main. The execution of the program always starts from the main function and ends with the main function. The main function can call other functions to do some special task.

C Program to Reverse a Number Using Function

From the operator’s topic, we know that the modulus operator (%) can be used to find the last digit of the number. Similarly, the division operator (/) can be used to remove the last digit of the number.

#include<stdio.h>
int findReverse(int n)
{
   int sum=0;
   while (n!=0)
   {
     sum = sum*10 + n%10;
     n /= 10;
   }
   return sum;
}

int main()
{
   int number, reverse;

   printf("Enter a positive interger: ");
   scanf("%d", &number);

   reverse = findReverse(number);

   printf("The reverse of %d is: %d", number, reverse);

   return 0;
}

Output for different test-cases:-

Enter a positive integer: 12345
The reverse of 12345 is: 54321

Enter a positive integer: 852314
The reverse of 852314 is: 413258

In this C program to reverse a number using function, we defined a function findReverse() which return type is int and takes an int argument. Inside the findReverse() function sum is declared and initialized with value 0.

PrepBytes
Use Code KNOWPROGRAM10 to get FLAT 10% OFF on all Courses

Now, using the while loop the last digit of number n is calculated by using the modulus operator (n%10), and the last digit is added as sum = sum*10 + n%10; After that, the last digit of the number is removed by using the division operator (n /= 10;). Finally, the sum value is returned to the caller function main.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

1 thought on “C Program to Reverse a Number Using Function”

Leave a Comment

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