0% found this document useful (0 votes)
4 views22 pages

Factorial and Fibonacci Functions in C

The document provides code examples for calculating factorials and Fibonacci numbers using recursion in C. It includes the definitions of the factorial and Fibonacci functions, along with sample main functions to prompt user input and display results. Additionally, it hints at a program for summing even or odd numbers up to a specified number, though details are not provided.

Uploaded by

alexbenjamin6996
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views22 pages

Factorial and Fibonacci Functions in C

The document provides code examples for calculating factorials and Fibonacci numbers using recursion in C. It includes the definitions of the factorial and Fibonacci functions, along with sample main functions to prompt user input and display results. Additionally, it hints at a program for summing even or odd numbers up to a specified number, though details are not provided.

Uploaded by

alexbenjamin6996
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

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

You might also like