Convert a given string into integer using recursion

#include
using namespace std;

int con(char * a,int n)
{
int sum,digit=0;

if(n==0)
return 0;

else{
	int digit=a[0]-'0';
	cout<<digit;
	con(a+1,n-1);
	 }

}

int main()
{

char a[]={‘6’,‘2’,‘3’,‘4’,‘4’};
int b=5;
con(a,b);
return 0;
}

//is my code correct?

In this problem, you are required to convert the string into the corresponding integer.
But your code is instead printing the digits.

Input:“62344”
Output: 62344 // a conversion that can be used later.

Also, the way you are declaring the string. You would get an error.

Try to figure out these two things.

If you still have doubts, feel free to ask.

could you plzz give me its solution…

I have modified your code:

#include
using namespace std;

int con(char * a,int n)
{
if(n==1)
return *a - ‘0’; //*a will return the value at a[0]
else
return (10 * con(a, n - 1) + a[n-1] - ‘0’);
}

int main()
{

char a[]=‘62344’;
int b=5;
con(a,b);
return 0;
}

I would suggest you to dry run this code to understand the logic behind the exit condition and the recursion statement.

Give a like if it is helpful.:wink:

2 Likes

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.