Hey Programmers,
Is there any better way to write the below recusive functions, plz help me so i can improve my programming...

1-
Write a recursive function that takes a nonnegitive integer and returns the sum of its digits,

int DigitSum(int n){
	if(n == 0){
		return 0;
	}else{
		return (n%10) + DigitSum(n/10);  
	}

}

2-
Write a recursive function DigitalRoot(int n) that returns the digital root of its arguments.

int DigitSum(int n){
	if(n == 0){
		return 0;
	}else{
		return (n%10) + DigitSum(n/10);  
	}

}

int DigitRoot(int n){
	if((n/10) < 1){
		return n;		
	}else{
		return DigitRoot(DigitSum(n));
	}
}

3- Reverse string

string Reverse(string str){
	if(str.length()==1){
		return str;
	}else{
		return str[str.length()-1] + Reverse(str.substr(0,str.length()-1));
	}
}

4-
write a recursive function to convert integer into string.

string IntToString(int n){
	if(n==0){
		return "";
	}else{
		return IntToString(n/10) + (char)((n%10)+48);
	}
}

Dani AI

Generated

Good start, . The recursive ideas shown in the thread are correct in spirit, but they miss a few practical points: handle zero and negative inputs, watch for stack depth, and prefer standard-library helpers where allowed. correctly flagged the zero case, ’s caution about recursion is relevant for large inputs, and ’s tail-call note is useful — but remember the C++ standard does not guarantee tail-call optimization, so don’t rely on it for deep recursion.

A few safer, clearer alternatives:

Iterative digit-sum (fast, no stack risk):

int digitSumIter(unsigned long long n) {
    int sum = 0;
    while (n) { sum += n % 10; n /= 10; }
    return sum;
}

O(1) digital root (no loops):

int digitalRoot(unsigned long long n) {
    return n == 0 ? 0 : 1 + (int)((n - 1) % 9);
}

For reversing a string prefer the standard algorithm (simple and efficient):

void reverseInPlace(std::string &s) {
    std::reverse(s.begin(), s.end());
}

A robust Int->String converter that handles zero, negatives and INT_MIN without recursion (or just use C++11’s std::to_string):

std::string intToStringSafe(int n) {
    if (n == 0) return "0";
    bool neg = n < 0;
    unsigned long long x = neg ? -(long long)n : (unsigned long long)n;
    std::string s;
    while (x) { s.push_back(char('0' + (x % 10))); x /= 10; }
    if (neg) s.push_back('-');
    std::reverse(s.begin(), s.end());
    return s;
}

Final tips: if this is an assignment requiring recursion, convert algorithms to tail-recursive variants (add an accumulator) and explicitly handle base cases (0, negatives). Otherwise, prefer iterative forms and standard helpers for correctness and performance.

Recommended Answers

All 5 Replies

>>write a recursive function to convert integer into string.
Your function will work good for all positive integer but would fail when N=0.
IntToString(0)=""

Hi,

Not sure if recursive is your assignment or not, bu if it's not ... you could do a far better job on some of the functions without it.

Recursive functions should be used as sparingly as possible as they are extremely slow...

>Recursive functions should be used as sparingly as possible as they
>are extremely slow
Yes. But looking at the other side of the coin, recursive function tend to be easy to model than iterative algorithms.
For say, fibonacci sequence, you can immediately model the function by applying the direct (recursive) definition while the iterative version will surely catch your brain for at least 2-3 minutes (if you are a beginner)

Recursive functions should be used as sparingly as possible as they are extremely slow...

Potentially slow. Compilers do not have to do a function call mechanism with the usual stack frame setup that has the lion's share of overhead. For some tail recursive functions, compilers can easily optimize them into iteration and there is no speed difference at all. The overhead of recursion is not usually enough to be a deciding factor, but the risk of stack overflow should always be considered.

Recursion should be used when it makes sense to do so. But when it makes sense depends on things like how much complexity is reduced by switching from iteration to recursion, how much risk of stack overflow there is, whether you need to break out of the recursive loop, and speed/memory usage.

For say, fibonacci sequence, you can immediately model the function by applying the direct (recursive) definition while the iterative version will surely catch your brain for at least 2-3 minutes (if you are a beginner)

Then those 2-3 minutes are time well spent. :D Unless previous results are cached, the recursive algorithm for calculating the fibonacci sequence is very inefficient. If you are a beginner, you probably will not think about this, and the 2-3 minutes of catching your brain will save you from using a really bad algorithm. ;)

it is my assignment :(

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.