Home > Mobile >  Reverse of a number using recursion
Reverse of a number using recursion

Time:10-09

The reverse of the number is getting printed many times. How do I print it just once?

For example, if I give input as 1234 then the output is coming out as 4321 4321 4321 4321.

#include <stdio.h>
#include <stdlib.h>

//function declaration
void printReverse(int);

int main()
{
    int n;
    printf("\n\t\t\t\t\t\tThis program prints reverse of a given number");
    printf("\nEnter a number: ");
    scanf("%d",&n);

    //if someone enters 0
    if(n==0)
    {
        printf("%d",n);
        exit(0);
    }
    //function call
    printReverse(n);
    
    return 0;
}

void printReverse(int n)
{
    static int rev=0; 
    
    //base case
    if(n) 
    {
        int rem = n % 10;      
        rev = rev*10   rem; 
        printReverse(n/10); 
    }
    printf("%d ",rev);
    
    
}

CodePudding user response:

The way your printReverse function is currently written, the last line (printf("%d ",rev);) will always be executed whenever the function is called, because there is no code path through the function that skips that line. So, when the recursion has reached the point where the given argument is zero, you will get that line being called each time on the 'rewind' of the stacked, recursive calls (once for each digit in the initial n).

To fix this, you can either enclose that printf line in an else block:

void printReverse(int n)
{
    static int rev = 0;
    if (n) {
        int rem = n % 10;
        rev = rev * 10   rem;
        printReverse(n / 10);
    }
    else { // Only print the result when we're finished (n = 0):
        printf("%d\n", rev);
    }
}

Or, accomplishing much the same thing, add a return statement after you make the recursive call:

void printReverse(int n)
{
    static int rev = 0;
    if (n) {
        int rem = n % 10;
        rev = rev * 10   rem;
        printReverse(n / 10);
        return; // Don't print on the rewind from recursion
    }
    printf("%d\n", rev);
}

CodePudding user response:

C Program to reverse a given number using Recursive function

based on enter image description here

  • Related