top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the rules of recursion?

0 votes
355 views
What is the rules of recursion?
posted Dec 19, 2016 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote
 
Best answer

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

I think with the above example I have given your answer.

answer Dec 20, 2016 by Arshad Khan
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.

+4 votes

Addition to this,

Can we consider "a car a man a maraca" as palindrome string?
Click here To see similar kind of palindrome strings,
Are they really a palindrome?

+4 votes

Given a binary tree, print all its root to leaf paths with recursion. For example, consider the following Binary Tree,
enter image description here

complexity must be O(n) or O(nlogn).

...