# Recursive Implementation of atoi() in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

We are given a string containing a number. The goal is to find the equivalent number using the recursive atoi() method. int atoi(const char *str) converts the string argument str to an integer (type int).

## Example-:

Input − Str[] = "58325"

Output − The Equivalent decimal is :58325

Explanation − The string contains the equivalent number 58325

Input − Str[] = "00010"

Output − The Equivalent decimal is :1

Explanation − The string contains the equivalent number 10.

## Approach used in the below program is as follows

In this approach we are using the recursive function recurAtoi() which takes input string and its length and for each character convert it to decimal and multiply it with 10. Add previous results to it.

• Take the input string Str[] containing a number.

• Calculate its length using strlen(Str).

• Function recurAtoi(char *str, int len) takes input and returns the number calculated using recursive atoi() functionality.

• If length is 1 return digit *str -’0’.

• Take temp=10*recurAtoi(str,len-1).

• And set temp=temp+str[len-1]-'0'.

• At the end return temp.

• Print result.

## Example

#include <bits/stdc++.h>
using namespace std;
int recurAtoi(char *str, int len){
if (len == 1){
return *str - '0';
}
int temp=10*recurAtoi(str,len-1);
temp=temp+str[len-1]-'0';
return (temp);
}
int main(void){
char Str[] = "58325";
int length = strlen(Str);
cout<<"Equivalent decimal :"<<recurAtoi(Str, length);
return 0;
}

## Output

If we run the above code it will generate the following Output

Equivalent decimal : 58325