# 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 the implementation of the idea.

## C++

 `// Recursive C program to compute atoi() ` `#include ` `#include ` ` `  `// 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 ` `    ``// and add last digit ` `    ``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; ` `} `

## Python3

 `# Python3 program to compute atoi() ` ` `  `# Recursive function to compute atoi() ` `def` `myAtoiRecursive(string, num): ` `     `  `    ``# base case, we've hit the end of the string, ` `    ``# we just return the last value ` `    ``if` `len``(string) ``=``=` `1``: ` `        ``return` `int``(string) ``+` `(num ``*` `10``) ` `         `  `    ``# add the next string item into our num value ` `    ``num ``=` `int``(string[``0``:``1``]) ``+` `(num ``*` `10``) ` `     `  `    ``# recurse through the rest of the string ` `    ``# and add each letter to num ` `    ``return` `myAtoiRecursive(string[``1``:], num) ` ` `  `# Driver Code     ` `string ``=` `"112"` ` `  `print``(myAtoiRecursive(string, ``0``)) ` ` `  `# This code is contributed by Frank-Hu-MSFT `

Output:

`112`

My Personal Notes arrow_drop_up

Improved By : fhu004

Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.