How to avoid stack overflow in infintie recursion? [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I'm trying to simulate functional programming in c++ , I'm stucking on "wait" function , assume I want to wait for 100 seconds without using any kind of loops , just recursion . How can I avoid Stack Overflow ?

Make the calls tail-recursive and hope for the compiler to reuse the stack frames. Although I don't think C++ compilers are required to perform this optimization, so all you can do is to rely on implementation.
But why do this if you can simply this_thread::sleep_for()?

I think the real question should be:
How do functional programming languages like Scheme and Haskell use recursion to achieve looping without causing a stack overflow?
And the answer is: they use a trick called tail-recursion to turn the recursive call into a goto. So you'll have to either find a C++ compiler that implements tail-recursion, or simulate it in your code.
Here's an example to give you an idea of how tail-recursion works:
countdown x = if x == 0
then 0
else countdown (x - 1)
countdown 1000000
Notice that, in the recursive step, it just calls the function with different arguments, and then returns its value. So the compiler "cheats" by converting it into code that works like this:
int countdown(int x) {
start:
if (x == 0) return 0;
x = x - 1;
goto start;
}
By the way, if you have to write your code to take advantage of tail-recursion. It doesn't just automatically work. More information here: What is tail recursion?

using a branching recursion. think about a grossly non-optimal recursive fibonacci program. They have exponential running time vs required stack depth.

Related

What is better for performance? Infinitive loop with if or normal loop? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
i often see game engines doing:
for(;;) if(!frame()) break;
Why arent they just writing:
while(frame());
or if they want to use for:
for(;frame(););
is it possible that with for(;;) or while (true) the compiler can optimize more because the condition is always true?!
This is horses for courses.
Any good optimising compiler will generate the same code in these circumstances.
Old-fashioned folk rely heavily on for(;;) as most mainsteam compilers don't generate a warning for that when warnings are set "normally". In my opinion at least while(frame()); is a little clearer although some folk don't like empty loop bodies, and the loop body of the first way is not empty.
From cppreference on for loops:
The above syntax [a for loop] produces code equivalent to:
{
init_statement
while ( condition ) {
statement
iteration_expression ;
}
}
Compilers do not read cppreference, but they also do know that each for loop can be written as a while loop and vice-versa.
The reason you see it often is probably a matter of convention. And we can only guess why it was choosen. Let me speculate...
Consider this loop:
for (int i=0;i < N; ++i);
{
// do something
}
Can you spot the mistake? Good compiler warn about it, but in my opinion the potential for such mistakes or to confuse a loop without body with such mistake is reason enough to avoid loops without body when it is possible for no cost.
is it possible that with for(;;) or while (true) the compiler can
optimize more because the condition is always true?!
No, effectively the condition is the same in all three versions.

Obtaining an algorithm [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Let's say I have a variable a and b. Now I want to find a value for c such that the fraction a / c is a positive integer, and where c is as close to b as possible.
For example: a = 100 and b = 30.
In this case I want c to be 25; because a / c is an integer, and c is as close as b for which this holds.
Any ideas how I can program a function in C++ which does exactly this?
Find the factors of a. (search web for methods)
Scan resulting list for minimum difference vs b.
Is this a homework assignment? Either way, think about how you would solve this problem without writing any code. A good algorithm comes from a good design. Break the problem down into pieces and walk through some more examples. For example, how would you solve the problem of determining whether the division results in an integer value? Hint: There is a different operator you could use as opposed to division to achieve this easily. Now, how would you solve the problem of determining what number to start at for c in the algorithm? Do not write any code until you have the pseudocode figured out.

Is there anything like 'minimizing stack overflow of an array' in C language? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Someone was telling me about minimizing the stack overflow of an array in C that i can do it by filling an array from both sides that is left to right and right to left, something like that. but basicly i did not understand. please explain for better understand. thank you.
The stack is where automatic variables are allocated
You can overflow it by allocating huge objects int x[10000000000] or with very deep levels of recursion. The stack can be further limited in multithread environment's stack allocation per thread
The way to avoid allocating on the stack is to have a pointer and allocate on the heap using malloc (this is the the C version of calling new) but this increases code complexity by requiring a matching call to free.
The way to reduce deep recursion is by possibly finding a shallower (generally more efficient) recursive algorythm. Possibly filling the array from both sides is results in shallower recursion.
The generally better way however is to translate the recursive algorythm to an iterative (looping) equivalent (which can generally be done with the optimized recursion as well). Looking at a trivial example:
The following recursion:
unsigned mult(unsigned a, unsigned b)
{
return b ? a+mult(a, b-1) : 0;
}
Becomes the following iterative equivalent:
unsigned mult(unsigned a, unsigned b)
{
unsigned ret=0;
while (b-- > 0)
ret+=a;
return ret;
}

Which function should I use so that it works just like GOTO statement? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am learning c++ and I have this question.
I have a file01.cpp with loops and if else statement.
e.g.
File01.cpp has
If(x<0)
cout<<x<<endl;
else
GOTO file02.cpp line number 29;
This the the rough idea what I want to do. I don't know how can I do this, I preferrably don't want to use GOTO statement.
Which function should I use so that it works just like GOTO statement?
You shouldn't. The point of avoiding goto is to avoid the kind of spaghetti code it produces, not to avoid the literal word goto. By substituting some other function for goto, you've completely missed the point. You need to restructure your program, and invoke a function, not a line number.
To answer the question you've actually asked, what you should use for goto-like behaviour is goto; there is no "function" that behaves like goto, because goto already does that. But the more important answer is, don't do what you're doing, rethink how your program is structured.
You want to factor out that code you want to call (file02.cpp line number 29) into a function and call that function from file01.cpp and file02.cpp line number 29
This is not how you would structure your c++ or c programs. Instead you would use a functional approach. (err I mean Procedural)
By this I mean you would have a function inside a header file, and you would call that function. Not goto it.

Any good recursive tutorials? Python? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 9 years ago.
Improve this question
Wondering if anyone could point me towards a good recursion tutorial. I am a bit rusty on it as I learned about it in my Data Structures class first semester. Would like to brush up on my recursion...any help?
Consider this.
More seriously…
Recursion is a way of solving problems that have a clearly defined base case (or cases, btu I'm keeping it simple here.)
For examples, the commonly cited factorial problem is a great one.
What does factorial do? Let's see some examples:
factorial(0) = 1
factorial(1) = 1
factorial(2) = 2
factorial(3) = 6
factorial(4) = 24
The factorial of a number is that number multiplied by the factorial of the number that comes before it, unless (now, this is the base case) the number is 0. The factorial of 0 is 1. (You can't take the factorial of a negative number; only positive integers.)
So we have our clearly defined base case. And we know what to do with numbers that aren't our base case (we multiply them times the factorial of the number one less than it.) We're ready to write our function.
def factorial(x):
if x == 0: # this is our base case
return 1 # and this is what we do when we see it
else: # this is what we do with all other numbers
return x * factorial(x-1)
So you
Clearly define your base case.
Find a way to reduce your problem from a non-base case to the base case.
Formally express that in a function that (when it's simple!) looks like
function:
if base case:
this
else:
something + function(something closer to the base case)
If you want something more advanced, Google's got a lot of info.
I would highly recommend watching MIT's intro to programming course.
Lecture 4 talks about recursion.