# Recursive Implementation of atoi()

0
189

## atoi() function takes an string(which is a number) as an argument and returns its value

### Example

INPUT
s = “33”

OUTPUT
33

In the above example, we are passing 33 as a string and the output is a value

## Algorithm

1. Separate the last digit and recursivley compute result for remaining n-1 digits
a. Multiply the result with 10 and add the obtained value to last digit

## C++ Program

``````// Recursive C++ program to compute atoi()
#include <bits/stdc++.h>
using namespace std;

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

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

// Driver Program
int main(void)
{
char s[] = "33";
int n = strlen(s);
cout<<atoiRecursively(s, n)<<endl;
return 0;
}``````

Previous articleProgram to add two binary digits
If you have come this far, it means that you liked what you are reading. I am a software developer (graduated from BITS Pilani). I love writing technical articles on programming and data structures.