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 // 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; } |
chevron_right
filter_none
Output:
112
This article is contributed by Narendra Kangralkar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Recommended Posts:
- Write your own atoi()
- Recursive Functions
- Morse Code Implementation
- Implementation of Affine Cipher
- Recursive Bubble Sort
- Modular exponentiation (Recursive)
- Recursive Insertion Sort
- Bitwise recursive addition of two integers
- Recursive Practice Problems with Solutions
- Recursive program to print all subsets with given sum
- Recursive program for prime number
- Recursive program to generate power set
- Recursive Program for Binary to Decimal
- Recursive function to do substring search
- Pattern Occurrences : Stack Implementation Java



