Introduction

Reversing a number involves changing its digits’ order. For example, reversing 1234 results in 4321. We can achieve this using recursion by isolating the last digit and combining it with the reversed version of the remaining digits.

#include <stdio.h>

int reverseNumber(int num, int reversed) {
    // Base case: if num is 0, return the reversed number
    if (num == 0) {
        return reversed;
    }
    // Recursive case: add last digit to reversed number
    reversed = reversed * 10 + (num % 10);
    return reverseNumber(num / 10, reversed);
}

int main() {
    int number;
    printf("Enter a number: ");
    scanf("%d", &number);

    int reversed = reverseNumber(number, 0);
    printf("Reversed number: %d\n", reversed);

    return 0;
}

Explanation

  1. Function Definition:
    • The function reverseNumber takes two parameters: num (the number to reverse) and reversed (the reversed number so far).
    • Base Case: If num is 0, it returns the reversed number, ending the recursion.
    • Recursive Case:
      • The last digit of num is obtained using num % 10.
      • The reversed number is updated by multiplying it by 10 (to shift left) and adding the last digit.
      • The function calls itself with the remaining digits (num / 10) and the updated reversed number.
  2. Main Function:
    • It prompts the user to input a number.
    • It calls reverseNumber with the input number and initializes reversed to 0.
    • Finally, it prints the reversed number.

Input and Output Example

Input:

Enter a number: 1234

Output:

Reversed number: 4321

Conclusion

This C program successfully reverses a number using recursion. The recursive approach breaks down the problem by handling one digit at a time, making it easy to understand and implement. While this method is efficient for relatively small numbers, be cautious with large numbers due to potential stack overflow issues with deep recursion.

Leave a Reply

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

Verified by MonsterInsights