Factorials
• 5! = 5 * 4 * 3 * 2 * 1
int fact(int k)
• 5! = 5 * 4!
• 4! = 4 * 3! k!=k*(k-1)!
{
• 3! = 3 * 2! if (k == 0)
• 2! = 2 * 1! return 1;
• 1! = 1 * 0! else
• 0! = 1 return k*fact(k-1);
}
#include <stdio.h>
int fact(int k)
{
if (k == 0)
return 1;
else
return k*fact(k-1);
}
int main()
{ int n, result;
printf("Enter number: ");
scanf("%d",&n);
result = fact(n);
printf("Factorial is %d : ", result);
return(0);
}
Example Using Recursion: The Fibonacci Series
• Fibonacci series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
Each number is the sum of the previous two
int fibo ( int n )
The Rule is Xn = Xn-1 + Xn-2 {
• F( n ) = F( n - 1 ) + F( n - 2 ) if (n == 0 || n == 1)
return n;
F(0)=0, F(1) = 1
else
return fibo( n - 1) + fibo( n - 2 );
}
#include <stdio.h>
int fibo ( int n )
{
if (n == 0 || n == 1)
return n;
else
return fibo( n - 1) + fibo( n - 2 );
}
int main()
{
int n, result;
printf("Enter number: ");
scanf("%d",&n);
result = fibo(n);
printf("Fibonacci = %d\n",result);
return(0);
}
Program: Sum of Even or Odd Numbers up
to N