0% found this document useful (0 votes)
8 views

Recursion

The document contains two C programs that demonstrate recursion. The first program calculates the factorial of a given positive integer, while the second program generates the Fibonacci series up to a specified number of elements. Both programs utilize recursive function calls to achieve their respective tasks.

Uploaded by

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

Recursion

The document contains two C programs that demonstrate recursion. The first program calculates the factorial of a given positive integer, while the second program generates the Fibonacci series up to a specified number of elements. Both programs utilize recursive function calls to achieve their respective tasks.

Uploaded by

khushisahu.0613
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Program for Recursion

//Program to print factorial of a number using recursion

#include<stdio.h>
long int multiplyNumbers(int n);
int main() {
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n));
return 0;
}

long int multiplyNumbers(int n) {


if (n>=1)
return n*multiplyNumbers(n-1);
else
return 1;
}

Logic explanation:
//Program to print Fibonacci series using recursion
#include <stdio.h>
// fibonacci() funtion definition
int fibonacci(int num)
{
// first base condition check
if (num == 0)
{
return 0; // retuning 0, if condition meets
}
// second base condition check
else if (num == 1)
{
return 1; // returning 1, if condition meets
}
// else calling the fibonacci() function recursively till we get to the base conditions
else
{
return fibonacci(num - 1) + fibonacci(num - 2); // recursively calling the fibonacc()
function and then adding them
}
}

int main()
{
int num; // variable to store how many elements to be displayed in the series
printf("Enter the number of elements to be in the series : ");
scanf("%d", &num); // taking user input
int i;
for (i = 0; i < num; i++)
{
printf("%d, ", fibonacci(i)); // calling fibonacci() function for each iteration and
printing the returned value
}

return 0;
}

You might also like