   # What is the rules of recursion?

37 views
What is the rules of recursion? posted Dec 19, 2016

+1 vote

There are two points which you have to remember while writing a recursion program.

1.The basic i.e a function calling itself (its called recursion)

``````int recursion(int number)
{
printf("My number is: %d\n", number);
return recursion(--number);
}
int main()
{
recursion(10);
return 0;
}
``````

2.There should be a break point, when your program should stop its execution else it will crash due to stack over flow.

``````int recursion(int number)
{
printf("My number is: %d\n", number);

if (number == 0) {   // it will stop the calling itself when number reaches to zero.
return 0;
}
return recursion(--number);
}

int main()
{
recursion(10);
return 0;
}
``````

Note:
# In 1st point the program will definitely crash [because there is no check which stop the calling of the function recursion()]
# In 2nd point the program will print 10 to 0 and then stop, the output will be

`````` My number is: 10
My number is: 9
My number is: 8
My number is: 7
My number is: 6
My number is: 5
My number is: 4
My number is: 3
My number is: 2
My number is: 1
My number is: 0
`````` answer Dec 20, 2016
Similar Questions
+1 vote

Write a recursive function:

``````int sum( int x, int max )
{
/* complete the code */
}
``````

that calculates the sum of the numbers from x to max (inclusive). For example, sum (4, 7) would compute 4 + 5 + 6 + 7 and return the value 22.

Note: The function must be recursive.

Can we consider `"a car a man a maraca"` as palindrome string? 