
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Recursive Implementation of atoi() in C++
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
- Related Articles
- String to Integer (atoi) in C++
- Write your own atoi() in C++
- Implementation of Stack in JavaScript
- Implementation of Queue in JavaScript
- How to create a customized atoi() function in C language?
- Array implementation of queue in C++
- Implementation of Dynamic Array in Python
- Implementation of a Falling Matrix in C++
- The implementation of import in Python (importlib)
- Python - Implementation of Polynomial Regression
- Implementation of connection-oriented services
- Implementation of Whale Optimization Algorithm
- RPA Implementation
- Checking implementation of interface IF_EX_IDOC_CREATION_CHECK in SAP ABAP
- Demonstrate a basic implementation of ‘tf.keras.layers.Dense’ in Python
