OverIQ.com

C Program to reverse the digits of a number using recursion

Last updated on September 24, 2020


The following is a C program to reverse the digits of a number using recursion:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**********************************************************
 Program to reverse the digits of a number using recursion 
 * 
 * Enter a number: 4321
 * 1234
 **********************************************************/

#include<stdio.h> // include stdio.h library
void reverse_num(int num);

int main(void)
{    
    int num;

    printf("Enter a number: ");
    scanf("%d", &num);       

    reverse_num(num);

    return 0; // return 0 to operating system
}

void reverse_num(int num)
{    
    int rem;

    // base condition
    if (num == 0)
    {
        return;
    }

    else
    {
        rem = num % 10; // get the rightmost digit
        printf("%d", rem);
        reverse_num(num/10);  // recursive call
    }

}

Try it now

Expected Output: 1st run:

1
2
Enter a number: 12345
54321

2nd run:

1
2
Enter a number: 1331 
1331

How it works #

The following figure shows how the evaluation of reverse_num(123) takes place:


Recommended Reading: