c recursion func revers number
Reversing a Number Using Recursion in C
Here is an example of a C program that uses recursion to reverse a number:
#include <stdio.h>
int reverse(int num);
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("Reversed number: %d\n", reverse(num));
return 0;
}
int reverse(int num) {
static int reversedNum = 0;
if (num != 0) {
reversedNum = reversedNum * 10 + num % 10;
reverse(num / 10);
}
return reversedNum;
}
Explanation of the Steps:
The program starts by including the necessary header file
stdio.h
for input/output operations.The
reverse
function is declared before themain
function. This function takes an integernum
as input and returns the reversed number.Inside the
main
function, a variablenum
is declared to store the input number from the user using thescanf
function.The
printf
function is used to display a message asking the user to enter a number.The
scanf
function is used to read the input number from the user and store it in thenum
variable.The
printf
function is used to display a message indicating the reversed number. Thereverse
function is called with thenum
variable as an argument.The
reverse
function is defined. It takes an integernum
as input and returns the reversed number.Inside the
reverse
function, a static variablereversedNum
is declared and initialized to 0. This variable will store the reversed number.The base case of the recursion is checked using an
if
statement. Ifnum
is not equal to 0, the recursion continues.Inside the
if
statement, thereversedNum
variable is updated by multiplying it by 10 and adding the remainder ofnum
divided by 10. This effectively adds the rightmost digit ofnum
to the reversed number.The
reverse
function is called recursively withnum
divided by 10 as the argument. This removes the rightmost digit fromnum
and continues the recursion.Once the base case is reached (i.e.,
num
becomes 0), the final reversed number is returned.The program execution returns to the
main
function, and the reversed number is displayed using theprintf
function.
Example Output:
Enter a number: 12345
Reversed number: 54321
Please let me know if you need any further assistance!