Update
This commit is contained in:
parent
275c83d379
commit
793eff5870
19 changed files with 2117 additions and 1835 deletions
40
recursion.md
40
recursion.md
|
@ -60,6 +60,46 @@ unsigned int factorial(unsigned int x)
|
|||
}
|
||||
```
|
||||
|
||||
Here is another example of elegant recursion: printing string backwards:
|
||||
|
||||
```
|
||||
#include <stdio.h>
|
||||
|
||||
void readAndPrintBackwards(void)
|
||||
{
|
||||
int c = getchar();
|
||||
|
||||
if (c != EOF)
|
||||
{
|
||||
readAndPrintBackwards();
|
||||
putchar(c);
|
||||
}
|
||||
}
|
||||
|
||||
int main(void)
|
||||
{
|
||||
readAndPrintBackwards();
|
||||
putchar('\n');
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
The program reads one character in each call of the function and holds its printing for when we're emerging back from the recursion dive. The terminating condition here the check for end of the string (`EOF`). You can test this for program by compiling it and passing it a string, e.g. `echo "catdog" | ./program` which should result in printing `godtac`. In [comun](comun.md) the same program would be written as:
|
||||
|
||||
```
|
||||
readAndPrintBackwards:
|
||||
<-
|
||||
|
||||
<? ?
|
||||
readAndPrintBackwards
|
||||
.
|
||||
|
||||
->
|
||||
.
|
||||
|
||||
readAndPrintBackwards
|
||||
```
|
||||
|
||||
Some problems, for example [Ackermann function](ackermann_function.md), [quick sort](quick_sort.md), [tree](tree.md) traversals or the mentioned factorial are said to be "recursive" because they are just most elegantly defined and/or solved with recursion, but as we've seen, there is no problem that would inherently require recursive function calls. There may exist Turing complete languages without recursion that can still solve all problems that any other language can.
|
||||
|
||||
How do the computers practically make recursion happen? Basically they use a [stack](stack.md) to remember states (such as values of local variables and return addresses) on each level of the recursive dive -- each such state is captured by so called **stack frame**. In programming languages that support recursive function calls this is hidden behind the scenes in the form of so called **[call stack](call_stack.md)**. This is why an infinite recursion causes stack overflow.
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue