Search This Blog
Welcome to 1printf(), your ultimate destination for C, C++, Linux, Data Structures, and Microcontroller programming! ๐ ๐นLearn advanced coding techniques in C& C++ ๐นMaster Linux internals & shell scripting ๐นDeep dive into Data Structures & Algorithms ๐นExplore Embedded Systems & Microcontrollers (8051,UART, RTOS) ๐นGet hands-on coding tutorials, project ideas,and interview preparation tips Whether you're a beginner or an experienced programmer, this channel will help you
Featured
- Get link
- X
- Other Apps
Reverse Number Using Recursion in C
๐ท C Program: Reverse Number Using Recursion
#include<stdio.h>
int reverse(int num, int rev)
{
if(num == 0)
{
return rev;
}
else
{
return reverse(num / 10, rev * 10 + num % 10);
}
}
int main()
{
int num, result;
printf("Enter the number:\n");
scanf("%d", &num);
printf("Before Reversing: %d\n", num);
if(num <= 0)
{
result = reverse(-num, 0);
printf("After Reversing: -%d\n", result);
}
else
{
result = reverse(num, 0);
printf("After Reversing: %d\n", result);
}
}
๐ Explanation:
This C program uses a **recursive function** to reverse a given number.
๐ธ The `reverse()` function takes two arguments:
- `num`: the original number (or part of it as recursion progresses)
- `rev`: the reversed number being constructed
๐ธ The base condition is when `num` becomes 0. At that point, the accumulated `rev` is returned.
๐ธ During each recursive call:
- The last digit of `num` (`num % 10`) is added to `rev` after multiplying `rev` by 10 to shift its digits left.
- Then `num` is reduced by removing the last digit using integer division (`num / 10`).
๐ธ Special handling is added to work with **negative numbers** by reversing the absolute value and printing a minus sign manually.
๐ Sample Output:
Enter the number:
1234
Before Reversing: 1234
After Reversing: 4321
Enter the number:
-786
Before Reversing: -786
After Reversing: -687
Enter the number:
0
Before Reversing: 0
After Reversing: 0
๐ท️ Keywords:
C reverse number program, recursion in C, reverse using recursion, reverse number logic, C number manipulation, beginner recursion program
Popular Posts
C++ Program for Hybrid Inheritance (All Types Together)
- Get link
- X
- Other Apps
C++ Program for Function Overloading Example
- Get link
- X
- Other Apps
Comments
Post a Comment