Professional Documents
Culture Documents
LECTURE-10 (Recursio N)
LECTURE-10 (Recursio N)
STRUCTURES
LECTURE 8
WHAT WILL BE THE OUTPUT
void fun( )
{
cout<< “Hello World”;
fun( );
}
void main( )
{
fun( );
}
WHAT WILL BE THE OUTPUT
void fun( )
{
fun( );
cout<< “Hello World”;
}
void main( )
{
fun( );
}
WHAT WILL BE THE OUTPUT
void fun(int i )
{
i=i-1;
cout<<i;
fun(i);
}
void main( )
{
Int j=8;
fun(j);
}
THINK?
• Recursive tasks:
• A task that is defined in terms of itself.
• A function that calls itself.
• With each invocation, the problem is reduced to a smaller task (reducing
case) until the task arrives at some terminal case.
RECURSION
if (terminal_condition) if (!terminal_condition)
terminal_case reducing_case
else
reducing_case
THE FACTORIAL FUNCTION
• n! = n * (n-1) * (n -2) * … * 2 * 1
• 5! = 5 * 4 * 3 * 2 * 1
• The same function can be defined recursively as fallows:
• 0! = 1 – terminal case
• n! = n * (n - 1)! - the reducing case
THE FACTORIAL FUNCTION
• 5! = 5 * 4!
• 4! = 4 * 3!
• 3! = 3 * 2!
• 2! = 2 * 1! Reducing Case
• 1! = 1! * 0!
• 0! = 1 - Terminal Case
FACTORIAL RECURSIVE FUNCTION
RECURSIVE CALLS IN FACTORIAL
RECURSIVE CALLS IN FACTORIAL
CLASS TASKS
• https://www.youtube.com/watch?v=B0NtAFf4bvU