Q:

C++ program to convert a string of number to integer

0

Write a recursive function to convert a given string into the number it represents. That is input will be a numeric string that contains only numbers, you need to convert the string into corresponding integer and return the answer.

Input format: Numeric string (string, Eg. "1234")

Output format: Corresponding integer (int, Eg. 1234)

Sample Input 1: "1231"

Sample Output 1: 1231

Sample Input 1: "12567"

Sample Output 1: 12567

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Algorithm:

  1. STEP 1: Declare a recursive function ‘stringToNumber ‘with parameters (int arr[] , int len)
  2. STEP 2: Base Case: if (len == 0), convert the character into number and return it.
  3. STEP 3: Recursive Case: Convert the character into number and store it in variable a.
  4. STEP 4: return a + 10 *stringToNumber(arr, len -1)

Example:

    Input = "23"
    First Traversal = 2,
    Second Traversal = 20 + 3,
    Result = 23

C++ program:

#include <bits/stdc++.h>
using namespace std;

//To find length of the string
int length(char input[]){
	int len = 0;
	for(int i =0;input[i] != '\0';i++){
		len++;
	}
	return len;
}

//Helper Function
int stringToNumber(char input[], int last){
	//Base Case
	if(last == 0){
		return input[last] - '0';
	}
	//Recursive Call
	int smallAns = stringToNumber(input,last-1);       
	int a = input[last] - '0';
	return smallAns * 10 + a;
}

//Recursive Function
int stringToNumber(char input[]){
	int len = length(input);
	return stringToNumber(input,len-1);
}

int main(){
	char input[50];
	cout<<"Enter Input"<<endl;
	cin>>input;

	cout<<"The output/number is ";
	cout<<stringToNumber(input)<<endl;

	return 0;
}

Output

 

 

 

Enter Input
1234
The output/number is 1234

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now