Recursive Implementation of atoi()

The atoi() function takes a string (which represents an integer) as an argument and returns its value.

We have discussed iterative implementation of atoi(). How to compute recursively?

We strongly recommend you to minimize your browser and try this yourself first
The idea is separate the last digit, recursively compute result for remaining n-1 digits, multiply the result with 10 and add the obtained value to last digit.

Below is C implementation of the idea.

```// Recursive C program to compute atoi()
#include <stdio.h>
#include <string.h>

// Recursive function to compute atoi()
int myAtoiRecursive(char *str, int n)
{
// Base case (Only one digit)
if (n == 1)
return *str - '0';

// If more than 1 digits, recur for (n-1), multiplu result with 10
return (10 * myAtoiRecursive(str, n - 1) + str[n-1] - '0');
}

// Driver Program
int main(void)
{
char str[] = "112";
int n = strlen(str);
printf("%d", myAtoiRecursive(str, n));
return 0;
}
```

Output:

`112`

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.
1.5 Average Difficulty : 1.5/5.0
Based on 6 vote(s)