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:

  1. The program starts by including the necessary header file stdio.h for input/output operations.

  2. The reverse function is declared before the main function. This function takes an integer num as input and returns the reversed number.

  3. Inside the main function, a variable num is declared to store the input number from the user using the scanf function.

  4. The printf function is used to display a message asking the user to enter a number.

  5. The scanf function is used to read the input number from the user and store it in the num variable.

  6. The printf function is used to display a message indicating the reversed number. The reverse function is called with the num variable as an argument.

  7. The reverse function is defined. It takes an integer num as input and returns the reversed number.

  8. Inside the reverse function, a static variable reversedNum is declared and initialized to 0. This variable will store the reversed number.

  9. The base case of the recursion is checked using an if statement. If num is not equal to 0, the recursion continues.

  10. Inside the if statement, the reversedNum variable is updated by multiplying it by 10 and adding the remainder of num divided by 10. This effectively adds the rightmost digit of num to the reversed number.

  11. The reverse function is called recursively with num divided by 10 as the argument. This removes the rightmost digit from num and continues the recursion.

  12. Once the base case is reached (i.e., num becomes 0), the final reversed number is returned.

  13. The program execution returns to the main function, and the reversed number is displayed using the printf function.

Example Output:

Enter a number: 12345
Reversed number: 54321

Please let me know if you need any further assistance!