C program to Reverse a Number | Program to Reverse a Number in C
1. Reversing a Number Using While loop
In this program, we will ask the user to enter the number which user want to reverse. The program will reverse the number using While loop.
Output:

Logic:
Let us consider user enter the number 1456. First the value of rev is 0.
1st Iteration: remainder=n%10 i.e remainder=1456%10=6 and rev=rev*10+remainder i.e rev=0*10+6=0+6=6.So, n=n/10 i.e 1456/10=145.
2nd Iteration: from the first iteration the value of n=145 and rev=6. remainder=n%10 i.e remainder=145%10=5 and rev=rev*10+remainder i.e rev=6*10+5=60+5=65. So, n=n/10 i.e 145/10=14.
3rd Iteration: from the second iteration the value of n=14 and reverse=65. remainder=n%10 i.e remainder=14%10=4 and the rev=rev*10+remainder i.e rev=65*10+4=650+4=654. So, n=n/10=14/10=1.
4th Iteration: from the third iteration the value of n=1 and rev=654. remainder=n%10 i.e remainder=1%10=1 and rev=rev*10+remainder i.e rev=654*10+1=6540+1=6541. So,n=n/10 i.e n=1/10=0
Now the value of n is 0 so the while loop will exit.
2. Using for Loop
Output:

In the above program, we have a user for loop instead of while loop so doesn’t be hesitated the logic behind the program is same.
3. C program to reverse a number using function
In this program, we will use the function in the main method so that the user will get the reverse of the input number after executing.
When the compiler reaches to Reverse_Integer(Number) then the compiler immediately jump to the Reverse_Integer function to perform its operation.
The logic behind the program is already discussed in the while loop program.
4. Using Recursion
Recursion means the function calls itself again and again till the condition becomes false.
Output:

In the above program, we have defined the user-defined function reverse_function which is called recursively.
Post a Comment