CSI 121 Lecture-No.10 (Fall 2021) - Recursion

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 17

Structured Programming Language

CSI 121/CSE 1111

Prof. Dr. A.K.M. Muzahidul Islam


Computer Science & Engineering (CSE)
United International University (UIU)

Fall 2021
Defining of Recursion

Recursion:
• The process in which a function calls itself
directly or indirectly is called recursion and
• the corresponding function is called as recursive
function.
Recursion
How Does Recursion Work?
What is baseMain Function
condition in recursion?

In recursive program, the solution to base case is


provided and solution of bigger problem is
expressed in terms of smaller problems.
int fact (int n){
if (n < = 1)//base case
return 1;
else
return n*fact(n-1);
return 0;
}
Example No. 1

Explain the functionality of following functions.


int fun1(int x, int y)
{
if(x == 0)
return y;
else
return fun1(x - 1, x + y);
}
Example No. 2

Explain the functionality of following functions.


// Assume that n is greater than or equal to 1

int fun1(int n){


if(n == 1)
return 0;
else
return 1 + fun1(n/2);
}
Example No. 3

Explain the functionality of following functions.


// Assume that n is greater than or equal to 1

int fun1(int n){


if(n == 1)
return 0;
else
return 1 + fun1(n/2);
}
/*C program to find factorial*/
#include <stdio.h>
//function for factorial
long int factorial(int n) {
if(n==1)
return 1;
return n*factorial(n-1);
}
int main() {
int num;
long int fact=0;
printf("Enter an integer number: ");
scanf("%d",&num);
fact = factorial(num);
printf("Factorial of %d is = %ld",num,fact);
printf("\n");
return 0; }
/*C program to print Fibonacci series*/
#include <stdio.h>

void getFibonacii(int a,int b, int n) {


int sum;
if(n>0) {
sum=a+b;
printf("%d ",sum);
a=b;
b=sum;
getFibonacii(a,b,n-1);
}
}
int main() {
int a,b,sum,n;
int i;
a=0;
//first term
b=1;
//second term
printf("Enter total number of terms: ");
scanf("%d",&n);
printf("Fibonacii series is : "); //print a and b as first and
second terms of series
printf("%d\t%d\t",a,b);
//call function with (n-2) terms
getFibonacii(a,b,n-2);
printf("\n");
return 0;
}
/*C program to print Fibonacci series*/
int main() {
int a,b,sum,n;
int i;
a=0;
//first term
b=1;
//second term
printf("Enter total number of terms: ");
scanf("%d",&n);
printf("Fibonacii series is : "); //print
a and b as first and second terms of series
printf("%d\t%d\t",a,b);
//call function with (n-2) terms
getFibonacii(a,b,n-2);
printf("\n");
return 0;
}
Example: Sum of Natural Numbers Using
Recursion
Exercises

https://www.w3resource.com/c-programming-exercises/recursion/index.php
THE END
Thank You

You might also like