You are on page 1of 11

CITY MONTESSORI SCHOOL

SECTOR-D LDA KANPUR ROAD, LUCKNOW


PHONE: 0522 2435690 FAX: 0522 2435690
Recursion (Chap – 11)
Definition: It is the process of solving a problem by reducing/breaking it to smaller
versions/parts of itself.

Recursion Vs Iteration:
i) Iteration is typically a faster process and uses less memory.
ii) Recursion is comparatively a slow process and uses large memory.

Recursive Method:
It is a programming technique whereby a procedure calls itself repeatedly until some
specific condition has been satisfied. Recursion is sometimes called circular definition.
The call to the method appears in the method‟s body itself.

Types of Recursion:
1) By Recursive Technique:-
i) Direct
ii) Indirect

2) By Number of Recursive Calls:-


i) Linear
ii) Non-Linear
iii) Binary
Direct Recursion Indirect (or Mutual) Recursion
A function call occurs inside the function definition. A function calls another function, which in turn makes a call to the
first one.
a( ) { a( ) {
….. …..
a( ); // calling itself b( ); // calling b( ) which again calls a( )
} }
b( ) {
…..
a( );
}

Linear Recursion Non - Linear Recursion Binary Recursion


Only one recursive call is made within the Multiple recursive calls are made within the Special case of non–linear recursion in
body of the function. For e.g. factorial, gcd body of the function by placing a single which a function makes two recursive calls
procedures. recursive call within a loop. to itself. For e.g. Fibonacci sequence, Binary
search procedures.
CITY MONTESSORI SCHOOL
SECTOR-D LDA KANPUR ROAD, LUCKNOW
PHONE: 0522 2435690 FAX: 0522 2435690
Parts of a Recursive Function
A recursive function is said to be well–defined, if it has the following two properties:

i) Base criteria: or base case is the case for which the function does not call itself.
This involves certain pre known value (called base value) or condition before
beginning a task that cause recursion to end. For e.g. Any number to the power 0 is 1
(Pre-known case)
ii) Recursive criteria: is the repetitive condition of a recursive method such that, each
time the function calls itself, the argument of the function must be closer to a base
value.

Mechanics of Recursion
i) Recursion works on the principle of a push–down stack.
ii) The memory space needed for each function call is placed on the stack, and then taken
off again when the function completes its execution. Thus, the last memory opened will be
the first memory to be closed which means the last function call returns to the previous
function call and so on.

Advantage:
Recursive code is typically much shorter than its iterative version. It makes the code compact.
Disadvantage:
i) Recursion tends to slow down execution of programs as it consumes extra storage
space. Each time a recursive call is made, the stack grows as a new memory space is
allocated to each local variable of the recursive routine. The computer may run out of
memory, if the recursive calls are not checked.
ii) Faulty programs are very difficult to debug.

Linear Recursive Functions:


A) Numeric Problems
E.g.1: To find the factorial of an integer n
n! = 1, if n = 0 or n = 1
n! = n x (n–1) x (n–2) x …..x 1, if n >1 non–recursive
3! = 3 x 2 x 1
3! = 3 x 2!
n! = n x (n–1)! Recursive

i) int fact(int n) { // returns n!


if(n < 2) return 1 ; // base case
return (n * fact(n–1)) ; // recursive case
}
ii) int fact(int n) { // returns n!
return (n < 2? 1 : (n * fact(n–1))) ; // base and recursive case
}
CITY MONTESSORI SCHOOL
SECTOR-D LDA KANPUR ROAD, LUCKNOW
PHONE: 0522 2435690 FAX: 0522 2435690

E.g.2: To find the sum of 1st n natural numbers


i) int sumnat(int n) {
if(n = = 0) return 0 ; // base case
return (n + sumnat(n –1)) ; // recursive case
}
ii) int sumnat(int n) {
return (n < 2? 0 : (n + sumnat(n–1))) ; // base and recursive case
}

E.g.3: To print the 1st n even or odd numbers


i) void even(int n) { // prints 1st n even numbers
if(n < 1) return ; // base case
even (n–1) ; // recursive case
System.out.print((n * 2) + “ ” ) ;
}
ii) void odd(int n) {
if (n > 0) { // prints 1st n odd numbers
odd (n–1) ; // recursive case
System.out.print((n * 2 – 1) + “ ”) ;
}
}
E.g.4: To print even numbers b/w 1 – n
void printeven(int n) {
if (n > 0) {
printeven (n–1 );
if (n%2==0) System.out.print(n+" ");
}
}
E.g.5: To find ‘a’ raised to power ‘b’ i.e. ab
i) int power(int a, int b) {
if (b = = 0) return 1 ; // base case
return (a * power(a, b–1)) ; // recursive case
}
ii) int power(int a, int b, int p) { // p = 1 initially
if (b = = 0) return p; // base case
return (power (a, b–1, p*a)); // recursive case
}
E.g.6: To find the product of a and b
int multiply(int a, int b) { // finds a * b, b >= 0
if(b = = 0) return 0 ; // base case
return (a + multiply(a, b–1)) ; // recursive case
}
CITY MONTESSORI SCHOOL
SECTOR-D LDA KANPUR ROAD, LUCKNOW
PHONE: 0522 2435690 FAX: 0522 2435690
E.g.7: To find the sum of a and b
int add(int a, int b) { // finds a + b, b >= 0
if (b = = 0) return a ; // base case
return (1 + add(a, b–1)) ; // recursive case
}
E.g.8: To find the difference of a and b
int sub(int a, int b) { // finds a – b, b >= 0
if (b = = 0) return a ; // base case
return (sub(a, b–1) – 1) ; // recursive case
}
E.g.9: Finding quotient of a and b
int div(int a, int b) { // finds a / b, b > 0
if (a < b) return 0 ; // base case
return (1 + div(a – b, b)) ; // recursive case
}
E.g.10: To find the remainder of a / b
int mod(int a, int b) { // finds a % b, b > 0
if (a < b) return a ; // base case
return (mod(a – b, b)) ; // recursive case
}
E.g.11: To find the gcd of a and b (Euclid’s method)
int gcd(int a, int b) {
if (b == 0) return a ; // base case
return (gcd(b, a%b)) ; // recursive case
}

B) Factor Operations
E.g.1: To find the sum of factors of a number excluding itself
int sumfactor(int n, int i) { // i = 1 initially
if (i = = n) return 0 ; // base case
if (n % i == 0) return (i + sumfactor(n, i+1));
return (sumfactor(n, i+1)) ; // recursive case
}
E.g.2: To count the factors of a number including itself
int countfactor(int n, int i) { // i = 1 initially
if (i > n) return 0 ; // base case
if (n % i == 0) return (1+ countfactor(n, i+1));
return (countfactor(n, i+1)) ; // recursive case
}
E.g.3: To check a prime number
boolean isprime(int n, int i) { // i = 2 initially
if (n = = i) return true ; // base case
if (n = = 1 || n % i == 0) return false; // base case
return (isprime(n, i+1)) ; // recursive case
CITY MONTESSORI SCHOOL
SECTOR-D LDA KANPUR ROAD, LUCKNOW
PHONE: 0522 2435690 FAX: 0522 2435690
}

C) Digit Extraction Problems


E.g.1: To count the number of digits in a number
int numLen(int n) {
if (n = = 0) return 0 ; // base case
return (1 + numLen(n/10)) ; // recursive case
}
E.g.2: To find the sum of digits of a number
int sumdigit(int n) {
if (n = = 0) return 0 ; // base case
return (n%10 + sumdigit(n/10)) ; // recursive case
}
E.g.3: To find the sum of cubes of digits of a number
int sumdigitcube(int n) {
if (n = = 0) return 0 ; // base case
int c = (int) Math.pow(n%10,3);
return (c + sumdigitcube(n/10)) ; // recursive case
}
E.g.4: To find the sum of even digits of a number
int sumevendigit(int n) {
if (n = = 0) return 0 ; // base case
if (n%10%2==0)
return (n%10+sumevendigit(n/10)); // recursive case
return (sumevendigit(n/10)) ; // recursive case
}
E.g.5: To count the frequency of a digit in a given number
int countdigit(int n, int d) {
if(n = = 0) return 0 ; // base case
if (n % 10 = = d)
return (1 + countdigit (n /10, d)); // recursive case
return (countdigit(n /10, d)) ; // recursive case
}
E.g.6: To find the reverse of a number
int revnum(int n, int r) { // r = 0 initially
if (n = = 0) return r ; // base case
return (revnum(n/10, r *10+n%10)) ; // recursive case
}
E.g.7: To check an automorphic number like 25
boolean isauto(int n, int sqr) { // returns true if n is present in the right of s(=n*n)
if (n = = 0) return true ; // base case
if (n % 10 != sqr % 10) return false; // base case
return (isauto(n/10, sqr/10) ; // recursive case
}
CITY MONTESSORI SCHOOL
SECTOR-D LDA KANPUR ROAD, LUCKNOW
PHONE: 0522 2435690 FAX: 0522 2435690
E.g.8: To remove zeroes from an integer n
int delzero(int n) {
if (n < 10) return n ;
int d = n%10;
if (d == 0)
return (delzero(n/10)); // recursive case
return (delzero(n/10) * 10 + d) ; // recursive case
}
E.g.9: To find the largest digit of integer n
int maxdigit(int n, int max) { / // max=first digit of n
if (n == 0) return max; // base case
int digit=n%10;
if (digit > max) return(maxdigit (n/10,digit)); // recursive case
return (maxdigit (n/10,max)); // recursive case
}
E.g.10: To convert a binary number to decimal
int binToDec(int bin,int i) { // i=0 initially
if (bin==0) return 0; // base case
int d=bin%10; // extract binary digit
return (d * (int) Math.pow(2,i) + binToDec(bin/10,i+1)); // recursive case
}
E.g.11: To convert a decimal number to binary
int decToBin(int dec,int i) { // i=0 initially
if (dec==0) return 0; // base case
int d=dec%2; // extract binary digit
return (d * (int) Math.pow(10,i) + decToBin(dec/2,i+1)); // recursive case
}
E.g.12: To convert a decimal number to binary
int decToBin(int dec) { // returns the binary equivalent of dec
if(dec==0) return 0;
return (decToBin(dec/2)*10+dec%2);
}

D) Series Problems
E.g.1: To print the first n terms of fibonacci series like 0, 1, 1, 2…
void fibser(int a,int b,int n) { // a=0, b=1 initially
if (n = = 0) return ; // base case
System.out.print(a+" ");
fibser(b, a+b, n–1); // recursive case
}
E.g.2: To print the sequence 1, 3, 6, 11, 20, n terms
void printser1(int n) {
if (n < 0) return ; // base case
printser1(n – 1 ); // recursive case
CITY MONTESSORI SCHOOL
SECTOR-D LDA KANPUR ROAD, LUCKNOW
PHONE: 0522 2435690 FAX: 0522 2435690
int a=(int) Math.pow(2,n) + n;
System.out.print(a+" ");
}
E.g.3: To print the sequence 1, 11, 111, 1111….. n terms
void printser3(int n, int a) { // a=1 initially
if(n > 0) { // recursive case
System.out.print(a+" ");
printser3(n-1,a*10+1);
}
}
E.g.4: To find the sum of the series 1 – 3 + 5 – 7 + ....+n terms
int sumser1(int n) {
if(n<1) return 0; // base case
int t=(2*n-1) * (int) Math.pow(–1 ,n–1); // recursive case
return (t + sumser1(n–1));
}
E.g.5: To return the sum of the series 1 + x2 + x3 +....+xn
int sumser2(int x,int n) {
if (n<0) return 0; // base case
int t = (int) Math.pow(x, n);
return (t+ sumser2(x, n–1)); // recursive case
}
E.g.6: To find the sum of the series 1 + 3 + 7 + 15 + 31....+n terms
int sumser3(int n) {
if (n<1) return 0; // base case
return ((int) Math.pow(2, n) –1 +sumser3(n–1)); // recursive case
}

E) String Recursive Problems


E.g.1: To find the length of a given string
int len(String s) {
if (s = = null || s.equals(“ “)) return 0 ; // base case
return (1 + len (s.substring(1))) ; // recursive case
}
E.g.2: To find the reverse of a string
String revstr(String s,int i) { // i = 0 initially
if (i == s.length( )) return "" ; // base case
char c = s.charAt(i) ;
return (revstr(s,i+1)+c) ; // recursive case
}
E.g.3: To convert the letters of a string to opposite case
String caseInvert(String s, int i) { // i = 0 initially
if (i = = len) return “ ” ; // base case
char c = s.charAt(i) ;
CITY MONTESSORI SCHOOL
SECTOR-D LDA KANPUR ROAD, LUCKNOW
PHONE: 0522 2435690 FAX: 0522 2435690
if (c >= „A‟ && c <= „Z‟) c = (char) (c + 32) ; // convert to lower case
else c = (char) (c – 32) ; // convert to upper case
return (c + caseInvert(i + 1)) ; // recursive case
}
E.g.4: To count uppercase letters in a given string
int noOfUpperCase(String s, int i) { // i = 0 initially
if (i == s.length( )) return 0 ; // base case
char c = s.charAt(i) ;
if (c >= 'A' && c <= 'Z') return(1 + noOfUpperCase (s,i+1)); // recursive case
return (noOfUpperCase (s,i+1)) ;
}
E.g.5: To create a vowel substring from a given string
String strvowels(String s, int i) { // i = 0 initially
if(i == s.length( )) return " "; // base case
char c = s.charAt(i) ;
if("aeiouAEIOU".indexOf(c) > -1)
return(c + strvowels (s,i+1)); // recursive case
return (strvowels (s,i+1)) ;
}

E.g.6: To count words that begin with a capital vowel


int countWord(String s, int i) { // i = 0 initially
char c1, c2 ;
if (i == s.length()) return 0; // base case
else {
c1 = s.charAt(i) ;
if (i == 0 || c1 == ' ') {
c2 = i == 0? c1: s.charAt(i+1) ;
if ("AEIOU".indexOf (c2) > -1)
return (1 + countWord (s,i+1));
}
return (countWord (s,i+1)) ; // recursive case
}
}
E.g.7: To check a palindrome string
boolean palin(String s, int i) { // i = 0 initially
if (i > len/2) return true ; // base case
if (s.charAt(i) != s.charAt(len –1– i)) return false ;
return (palin(s, i+1)) ; // recursive case
}

Binary Recursive Functions:


E.g.1: To find the nth Fibonacci term
0 1 1 2 ………
CITY MONTESSORI SCHOOL
SECTOR-D LDA KANPUR ROAD, LUCKNOW
PHONE: 0522 2435690 FAX: 0522 2435690
F0 F1 F2 F3 …..
F0 = 0 and F1 = 1 if n = 0 / 1
F3 = F2 + F1 = 1 + 1 = 2
Hence,
Fib (n) = n, if n = 0 or n = 1
Fib (n) = Fib (n–1) + Fib (n–2), if n > 1 // recursive

int fib(int n) {
if(n = = 0 || n = = 1) return n ; // base case
return (fib(n–1) + fib(n–2)) ; // recursive case
}
E.g.2: Finding a value x in a list A [ ] using binary search
int bsearch(int l, int u, int x) { // l = 0 , u = n–1 initially
// Assume that list A[ ] is an sorted array in ascending order
int m ;
if (l > u) return –1 ; // base case
m = (l + u) / 2;
if (x = = a[ m ]) return m ; // base case
return (x > a[m] ? bsearch (m+1, u, x) : bsearch (l, m–1, x)) ; // recursive case
}
Recursive Output Problems:
Q1. Give the output when meth (3) is called?
void meth(int ctr) {
if (ctr = = 0) System.out.println(“ ”) ;
else {
System.out.println (“Hello” +ctr);
meth (– –ctr) ;
System.out.println (“ ” +ctr);
}
}
O/P:
Hello3
Hello2
Hello1

0
1
2
Q2. Give the output for num (int n) when n = 5
public void num(int n) {
if(n > 0) {
System.out.print(n+“ ”) ;
num(n – 2) ;
System.out.print(n+“ ”) ;
CITY MONTESSORI SCHOOL
SECTOR-D LDA KANPUR ROAD, LUCKNOW
PHONE: 0522 2435690 FAX: 0522 2435690
}
}
O/P:
531135
Q3. Give the output when both „m‟ and „n‟ are equal to 5.
int check(int m, int n) {
if(n = = 1)
return –m– – ;
else
return (++m + check(m, – –n)) ;
}
O/P: 21
Q4.Give the output for num1 (int n) when n = 6
public String num1(int n) {
if (n <= 0) return “ ” ;
return num1(n–1) + n + “ ” ;
}
O/P:
123456
Q5. Give the output when s = “Program”, p1 = 0, p2 = 6.
public void func(String s, int p1, int p2) {
if (p1 > p2) return ;
else {
p1++; p2– –;
func (s, p1, p2) ;
System.out.print(s.charAt(p1)) ;
System.out.print(s.charAt(p2)) ;
}
}
O/P: roggorra

Q6. What will the function check ( ) return when the value of (i) n=25 and (ii) n=10?
int check (int n) {
if (n<=1) return 1;
if (n%2 == 0) return 1 + check(n/2) ;
else return 1 + check (n/2 + 1);
}
O/P: (i) 6 (ii) 5

Q7. What will the function smile ( ) return when the value of (i) n=9465 and (ii) n=3254?
String smile (int n) {
if (n > 2) {
if (n%2 != 0)
return smile (n/10) + “A”;
CITY MONTESSORI SCHOOL
SECTOR-D LDA KANPUR ROAD, LUCKNOW
PHONE: 0522 2435690 FAX: 0522 2435690
else return smile (n/10 + 2) + “B”;
}
else return “”;
}
O/P: (i) “ABBA” (ii) “ABAB”

You might also like