0% found this document useful (0 votes)
36 views19 pages

Java Recursive Function Examples

recursive problems

Uploaded by

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

Java Recursive Function Examples

recursive problems

Uploaded by

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

ISC Recurssion Questions

S QUESTIONS ON RECURSIVE FUNCTIONS Y

2020
QUESTION 8

[10]
Design a class BinSearch to search for a particular value in an array.
The details of the members of the class are given below:
Class name : BinSearch
Data members/instance variables :
arr[ ] : to store integer elements.
n : integer to store the size of the array.
Member functions/methods :
BinSearch( int nn ) : parameterized constructor to initialize n
= nn.
void fillarray( ) : to enter the elements in the array.
void sort( ) : sorts the array in ascending order using
any standard sortingtechnique.
int bin_search( int l, int u, int v ) : searches for the value ‘v’ using binary
search and recursive technique and
returns its locationif found otherwise
returns -1.
Specify the class BinSearch giving details of the constructor and functions void fillarray(
), void sort( ) and int bin_search(int, int, int). Define a main( ) function to create objects
and call the methods accordingly to enable the task.
ANSWER :
// The following program is successfully compiled and executed
import [Link].*;
class BinSearch
{
int arr[ ], n; // declaration of single dimensional array arr[ ] and ‘n’ for size of
the array
BinSearch( int nn ) // parameterized constructor
{
n = nn; //initialize argument ‘nn’ to ‘n’ as size of the array
arr = new int[ n ]; //creation of array which is declared above with size ‘n’
}//end of the parameterized constructor
void fillarray( ) // function to input integers in array arr[ ][ ] of size n
{ Scanner sr = new Scanner( [Link] );
for( int i = 0 ; i < n ; i ++ )
{
[Link]("Input number for the array = " ) ;
arr[ i ] = sr . nextInt( ); //input statement
}//closing for i loop
}//end of the function fillarray( )
void sort( ) // function to arrange/sort the array in ascending order using
BUBBLE SORT
{ for( int i = 0 ; i < n-1 ; i ++ )
{
for( int j = 0; j < n - i - 1; j ++ )
{
if( arr[ j ] > arr[ j + 1 ] ) //compare adjacent elements
{
ISC Recurssion Questions

int temp = arr[ j ]; arr[ j ] = arr[ j + 1 ]; arr[ j + 1 ] =


temp; //swap elements
}//end of if( ) block
}//end for j loop
}//end for i loop
}//end of the function sort( )
int bin_search( int l, int u, int v ) // function that uses binary search with recursive
technique
{
if( l > u ) //1st base case or condition
return -1;
else
{
int mid_index = ( l + u ) /2; //finding middle index of the sorted array
if( v == arr[ mid_index ] ) //check for presence of element ‘v’ i.e. 2nd base
case or condition
return mid_index; //returns the location/mid_index if ‘v’ is found
else if ( v > arr[ mid_index ] ) //3rd base case or condition
return( bin_search( mid_index + 1, u, v ) ); //calling function within
it self i.e. recursion
else
return( bin_search( l, mid_index - 1, v ) ); //calling function within it
self i.e. recursion
}//end of else block
}//end of the function bin_search( )
public static void main( String args[ ] ) //main function starts
{
Scanner br = new Scanner( [Link] ); //creating scanner object ‘br’
[Link]("Enter the size of the array : " ) ;
int s = br . nextInt( );
BinSearch obj = new BinSearch( s ); // making object of class ‘obj’ and
passing ‘s’ to ‘nn’
obj . fillarray( ); // calling function to input elements in the array of size ‘n’
obj . sort( ); // calling function to sort the array in ascending order using
Bubble sort
[Link]("Enter the element that you want to search : " ) ;
int num = br . nextInt( );
int found = obj . bin_search( 0, s - 1, num ); // calling recursive function to do
binary search
if( found == -1) //means element ‘num’ not found
[Link]("The element " + num + " is not found in the list " ) ;
else
[Link]("The element " + num + " is presnt at " + found + "
index/location " ) ;
}//end of the main( ) function
}//end of the class

2019
QUESTION 7

[10]
Design a class ArmNum to check if a given number is an Armstrong number or not. [A
number is said to be Armstrong if sum of its digits raised to the power of length of the number
is equal to the number]
ISC Recurssion Questions

Examples : 371 = 33 + 73 + 13
1634 = 14 + 64 + 34 + 44
54748 = 55 + 45 + 75 + 45 + 85
Thus 371, 1634 and 54748 are all the examples of Armstrong numbers.

The details of the class are given below:


Class name ArmNum
Data members/instance variables :
n : to store the number.
l : to store the length of the number.
Member functions/methods :
ArmNum( int nn) : parameterized constructor to initialize
the data members n = nn.
int sum_pow( int i ) : returns the sum of each digit raised to the
power of the length of the number using
recursive technique.
void isArmstrong( ) : checks whether the given number is an
Armstrong number by invoking the
function sum_pow( ) and displays the
result with a message.
Specify the class ArmNum giving the details of constructor and methods int sum_pow(int)
and void isArmstrong( ). Define a main( ) function to create an object and call the functions
accordingly to enable the task.
ANSWER :
// The following program is successfully compiled and executed
import [Link].*;
import [Link].*;
class ArmNum
{
int n, l; //data members required in the class
ArmNum( int nn ) //this is parameterized constructor
{
n = nn; //initialize value in argument ‘nn’ to data member ‘n’
}//end of parameterized constructor
int sum_pow( int i) // Recursive function to find digit to the power length of
the number
{
if( i == 0 ) // this is base case or condition to stop the recursion when true
return 0;
else
return( ( int ) Math . pow( i % 10 , l ) + sum_pow( i / 10 ) ); // sum_pow(i /10)
is Recursion
}//end of the recursive function sum_pow( )
void isArmstrong( ) // function that calls the Recursive function to check for
Armstrong
{
l = Integer . toString( n ) . length( ); //converts number ‘n’ into string then find and
store its length in l
int s = sum_pow( n ); // calling Recursive function by passing value of ‘num’ to
‘y’
if( s == n ) // check if sum of each digit to the power of length of the number
(s) is equal to ‘n’
[Link]( n + " is an Armstrong number");
else
[Link]( n + " is not an Armstrong number");
}//end of the function isArmstrong( )
ISC Recurssion Questions

public static void main( String args[ ] ) //main function starts here
{
Scanner sr = new Scanner( [Link] );
[Link]("Enter a number to check for Armstrong = ");
int num = sr . nextInt( ); // input a number
ArmNum obj = new ArmNum( num ); // making object ‘obj’ of the class and passing
num to nn
obj . isArmstrong( ); // calling function to check for Armstrong, this calls recursive
function sum_pow( )
}//the main( ) function ends here
}//the class ends here
2018
QUESTION 7

[10]
Design a class Perfect to check is a given number is a perfect number or not. [A number is
said to be berfect is sum of the factors of the number excluding itself is equal to the original
number]
Example : Input 6, its factors excluding itself (6) = 1, 2, 3, and its sum = 1+2+3 = 6, so 6 is
a perfect number.
The details of the class are given below:
Class name Perfect
Data members/instance variables :
num : to store an integer number.
Member functions/methods :
Perfect( int nn ) : parameterized constructor to initialize
the data member num = nn.
int sum_of_factors( int i ) : returns the sum of the factors of the
number (num), excluding itself, using
Recursive Technique.
void check( ) : checks whether the number (num) is a
perfect number by invoking the recursive
function sum_of_factors( ) and display
the result with an appropriate
message.
Specify the class Perfect giving the details of the constructor and methods int
sum_of_factors(int) and void check(). Define a main( ) function to create an object and call
the functions accordingly to enable the task.
ANSWER :
// The following program is successfully compiled and executed
import [Link].*;
import [Link].*;
class Perfect
{
int num; //data member as required in the class
Perfect( int nn ) //this is parameterized constructor
{
num = nn; //assign argument ‘nn’ to data member ‘num’
}//end of the parameterized constructor
int sum_of_factors( int i ) // Recursive function that returns sum of the factors of
argument ‘i’
{
if( i == num ) // this is base case or condition that allows the recursion till
condition is true
ISC Recurssion Questions

return 0;
else if( num % i == 0) //if num is divisible by ‘i’ then ‘i’ will be the factor of ‘num’
return ( i + sum_of_factors( i + 1 ) ); //add factor ‘i’ and call function
within itself i.e. recursion
else
return (sum_of_factors( i + 1 ) ); //call function within itself i.e.
recursion
}//end of the function sum_of_factors( )
void check( ) // this function calls the Recursive function to check for perfect
number
{
int sum = sum_of_factors( 1 ); // calling Recursive function by passing initial value
to argument ‘i’
if( sum == num ) // check if the sum of factors received in ‘sum’ is equal to ‘num’
[Link]( num + " is a Perfect number");
else
[Link]( num + " is not a Perfect number");
}//end of the function check( )
public static void main( String args[ ] ) throws IOException //main function starts
here
{
Scanner sc = new Scanner( [Link] ); //making object ‘sc’ of the scanner class
[Link]("Enter a number to check for perfect number = ");
int N = sc . nextInt( ); //this statement inputs a number in variable N
Perfect obj = new Perfect( N ); // making object ‘obj’ of the class and passes ‘N’ to
‘nn’ in the constructor
[Link]( ); // function call to check for perfect number. This function also calls
recursive function
}//the main( ) function ends here
}//the class ends here
2017
QUESTION 7.

[10]
A class Palin has been defined to check whether a positive number is a Palindrome number
or not.
The number ‘N’ is palindrome if the original number and its reverse are same.
The details of the class are given below:
Class name Palin
Data members/instance variables:
num : to store an integer number.
revnum : integer to store the reverse of the number.
Member functions/methods:
Palin( ) : constructor to initialize the data members with
legal values.
void accept( ) : to accept the number.
int Reverse( int y ) : reverses the parameterized argument ‘y’ and stores
it in ‘revnum’ using the Recursive Technique.
void check( ) : checks whether the number (num) is a Palindrome
number by invoking the recursive function reverse( ) and display the result with an
appropriate message.
Specify the class Palin giving the details of constructor and methods void accept( ), int
Reverse(int) and void check( ). Define a main( ) function to create an object and call the
functions accordingly to enable the task.
ANSWER :
// The following program is successfully compiled and executed
import [Link].*;
import [Link].*;
ISC Recurssion Questions
class Palin
{
int num, revnum; //data members required in the class
Palin( ) //this is non-parameterized or default constructor
{
num = 0; //assign 0 to variable num
revnum = 0; //assign 0 to variable revnum
}//end of the default constructor
void accept( ) // function to input the number
{
Scanner br = new Scanner( [Link] ); //making scanner object ‘br’
[Link]("Input a number = ");
num = br . nextInt( ); //input value in variable ‘num’ using scanner input
function
}//end of the function accept( )
int Reverse( int y ) // Recursive function that returns reverse of the number in
‘y’
{
if( y == 0 ) // this is base case or condition to stop the recursion when true
return revnum;
else
{
revnum = revnum * 10 + y % 10; //extract digit from ‘y’ and reverses it
return ( Reverse( y / 10) ); //call function within itself i.e. recursion
}//end else block
}//end of the function Reverse( )
void check( ) // function that calls the Recursive function to check for palindrome
{
int rev = Reverse( num ); // calling Recursive function by passing
// value of variable ‘num’ to ‘y’
if( rev == num ) // check if rev (reverse) of the number is equal to ‘num’
[Link]( num + " is a Palindrome number");
else
[Link]( num + " is not a Palindrome number");
}//end of the function check( )
public static void main( String args[ ] ) throws IOException //main function starts
here
{
Palin obj = new Palin( ); // making object ‘obj’ of the class
[Link]( ); // calling function to input a number in ‘num’
[Link]( ); // calling function to check for palindrome number. This function also
//calls recursive function Reverse( )
}//the main( ) function ends here
}//the class ends here
2016
QUESTION 7. [10]
A disarium number is a number in which the sum of the digits to the power of their respective
position is equal to the number itself.
Example: 135 = 11 + 32 + 53, hence 135 is a disarium number.
Design a class Disarium to check if a given number is disarium number or not. The details
of the class are given below::
Class name Disarium
Data members/instance variables:
num : to store an integer number.
size : integer to store the size of the number.
Member functions/methods:
Disarium( int nn ) : constructor to initialize the data num=nn and
size=0.
ISC Recurssion Questions
void countDigits( ) : counts the total number of digits and assigns it to
size.
int sumofDigits( int n, int p ) : returns the sum of the digits of the number (n) to
the power of their respective positions (p) using the
Recursive Technique.
void check( ) : checks whether the number (num) is a disarium
number and display the result with an appropriate
message.
Specify the class Disarium giving the details of constructor and methods void countDigits(
), int sumofDigits(int, int ), void check( ). Define a main( ) function to create an object and
call the functions accordingly to enable the task.
ANSWER :
// The following program is successfully compiled and executed
import [Link].*;
import [Link].*;
class Disarium
{
int num, size; //data members required in the class
Disarium(int nn) //this is parameterized constructor
{
num = nn; //assign or copy nn to data member num
size=0; //assign 0 to size
}//end of the parameterized constructor
void countDigit( ) // function to find total number of digits in the number stored in
num
{
int n = num; // copy or assign or initialize ‘num’ to another variable ‘n’
while( n>0 )
{
n = n / 10;
size++; // counting number of digits and store in variable size
}// end of while loop
}//end of the function countDigit( )
int sumofDigits( int n, int p ) // Recursive function that returns sum of digits of ‘n’
to
{ // the power of its position ‘p’
if( n == 0 ) // this is base case or condition to stop the recursion when true
return 0;
else
{
return ( sumofDigits( n/10, p-1 ) + (int) [Link]( n%10, p ) ); //call function
}//end else block
}//end of the function sumofDigits( )
void check( ) // function that calls the Recursive function to check for disarium
number
{
int S = sumofDigits( num, size ); // calling Recursive function by passing
// ‘num’ to ‘n’ and ‘size’ to ‘p’
if( S == num ) // check if sum of digits of the power of its position (S) is equal to
‘num’
[Link]( num + " is a Disarium number");
else
[Link]( num + " is not a Disarium number");
}//end of the function check( )
public static void main( String args[ ] ) throws IOException //main function starts
here
{
Scanner br = new Scanner( [Link] ); // making scanner object ‘br’
[Link]("Input a number= ");
ISC Recurssion Questions

int Y = [Link]( ); // take input a number and store in Y


Disarium obj = new Disarium( Y ); // making object of class and pass ‘Y’ to ‘nn’
in the // parameterized constructor
[Link]( ); //calling function to count the digits of ‘num’
[Link]( ); //calling function to check for Disarium number. This function calls
// recursive function sumofDigits( )
}//the main( ) function ends here
}//class ends here
1 A class Admission contains the admission numbers of 100 students. The details of the members of the class are as follows: 2015
Class name Admission
Data members/instance variables:
Adno[ ] : integer array to store admission numbers.
Member functions/methods:
Admission( ) : constructor to initialize the array elements.
void fillArray( ) : to accept the elements of the array in ascending order.
int binSearch( int l, int u, int v ) : to search for a particular admission number (v) using binary
search and Recursive technique and returns 1 if ‘v’ is found otherwise returns -1.
Specify the class Admission giving the details of constructor and functions void fillArray( ) and int binSearch(int, int,
int). Define the main( ) function to create an object and call the functions accordingly to enable the task.

ANSWER :
// The following program is successfully compiled and executed
import [Link].*;
import [Link].*;
class Admission
{
int Adno[ ] = new int[ 100 ];//integer array declaration
Admission( ) //this is default constructor
{
for( int j=0; j<100; j++ )
{
Adno[ j ] = 0; //initialize array to zero
}//end of for( ) loop block
}//end of default constructor
void fillArray( ) //function to input 100 integers in the array declared above
{
Scanner br = new Scanner( [Link] ); //the following statement creates scanner object
for(int j = 0; j <100; j++ )
{
[Link]("Enter number in the array one by one in ascending order : = " );
Adno[ j ] = [Link]( ); //this is user input that stores at jth index in the array Adno[ ]
}//for loop closes here
}//end of function fillArray( )
int binSearch( int l, int u, int v ) //this function performs Binary search using Recursion
{
if( l > u ) //base case or condition no. 1
{
return -1;
}//end of if( ) block
else
{
int mid_index = ( l + u ) / 2; //finding middle index of the sorted array
if( v = = Adno[ mid_index ] ) //base case or condition no. 2
{
return 1; //returns 1 if ‘v’ is found at the ‘mid_index’
}
else if( v > Adno[ mid_index ] ) //base case or condition no. 3
{
return ( binSearch( mid_index + 1, u, v ) ); //call function within itself (Recursion)
}
else //this will run if (v<Adno[ mid_index])
{
return ( binSearch( l, mid_index - 1, v ) ); //call function within itself (Recursion)
}
}//end of else block
}//end of function binSearch( )
public static void main( String args[ ] ) //main function starts here
{
Scanner mx = new Scanner( [Link] ); //creating scanner object
Admission obj = new Admission( ); //creating object of the class
[Link]( ); //calling function to input elements/admission numbers in the array
[Link]("Enter admission number to search using binary search = " );
int num = [Link]( ); //taking user input, the number to be searched
int found = [Link]( 0, 99, num); //calling function to do binary search using
// Recursion , from here ‘0’ goes to ‘l’. ‘99’ goes to ‘u’ and ‘num’ goes to ‘v’ (‘num’ is to be searched)
ISC Recurssion Questions
if( found = = 1 )
[Link]( num + " is found in the admission numbers " );
else
[Link]( num + " is not found in the admission numbers " );
}//end of main function
}//end of the class
2 A class SeriesSum is designed to calculate the sum of the following series: 2014

2 4 6 8
x x x x xn
1! 3! 5! 7! ( n + 1)!
Sum =
The members of the class are given below:
Class name SeriesSum
Data members/instance variables:
x : to store an integer number.
n : to store number of terms.
sum : double variable to store the sum of the series.
Member functions/methods:
SeriesSum(int xx, int nn ) : constructor to assign parameters n=nn and x=xx.
double findfact( int m ) : to return the factorial of ‘m’ using Recursive technique.
double findpower( int x, int y ) : to return ‘x’ raised to the power ‘y’ using Recursive technique.
void calculate( ) : to calculate the sum of the series by invoking the two recursive
functions respectively.
void display( ) : to print the sum of the series stored in variable ‘sum’.
(a) Specify the class SeriesSum giving the details of constructor and functions double findfact(), double findpower(
), void calculate( ) and void display( ).
[8]
(b) State the two differences between iteration and recursion.
[2]

ANSWER (a):
// The following program is successfully compiled and executed
import [Link].*;
class SeriesSum
{
int x, n; double sum; //data members required in the class
SeriesSum(int xx, int nn) //this is parameterized constructor
{ x = xx; n = nn; sum=0.0; //assign or copy xx to x, nn to n and 0 to sum
}//end of parameterized constructor
double findfact( int a ) // this function uses RECURSION to return factorial of ‘a’
{
if( a==0 ) //this is base case or condition to stop the recursion
return 1;
else
return ( a * findfact( a-1 ) ); //calling function within itself, this is Recursion
}//end of function findfact( )
double findpower(int a, int b) // this function returns ‘ab’ using RECURSION
{
if( b==0 ) //this is base case or condition to stop the recursion
return 1;
else
return ( a * findpower( a, b-1 ) ); //calling function within itself, this is Recursion
}//end of function findpower( )
void calculate( ) //function that calls above two recrsive functions to find sum of series
{
for(int j = 2; j <= n; j+=2 )
{
double pw = findpower( x, j ); //calling recursive function by passing ‘x’ to ‘a’ & ‘j’ to ‘b’
double fac = findfact( j-1 ); //calling recursive function by passing ‘j-1’ to ‘a’
sum = sum + pw / fac; //dividing return values stored in ‘pw’, ‘fac’ and add to sum
}//for loop closes here
}//end of function calculate( )
void display( )
{
[Link]("Sum of the series="+ sum);
}//end of function display( )
public static void main( String args[ ] ) //main function starts here
{
SeriesSum obj = new SeriesSum( 2, 10 ); //object of class that passes ‘2’ to ‘xx’ & ‘10’ to nn’
[Link]( ); //calling function to find the sum of series
[Link]( ); //calling function to print the value of ‘sum’ stored in calculate( )
} } //end of main function and end of class

ANSWER (b):
The difference between the iteration and recursion is as:
Iteration: 1. The values of the control variable used in loop are written in the same memory location after each iteration, thus
at the end of iteration only last value of the variable remains in the memory.
2. The iteration executes faster as compared to recursion.
ISC Recurssion Questions
Recurssion: 1. The recursion creates a fresh memory during each recursive call, thus at the end of recursion all the values of
variable remains in all the memory locations that are created during recursion
2. As the recursion creates many memory locations so the memory overheads and the recursion executes slow.
3 An emirp number is a number which is prime backwards and forwards. Example: 13 and its reverse 31 are both prime numbers. 2013
Thus 13 is an emirp number.
Design a class Emirp to check if a given number is Emrip or not.
The details of the class are as:
Class name Emirp
Data members/instance variables:
n : stores an integer number.
rev : store the reverse of the number.
f : stores the dividor.
Member functions/methods:
Emirp(int nn ) : constructor to assign parameter nn to n (n=nn), 0 to rev and 2 to f.
int isprime( int x ) : using Recursive technique, check, if the number ‘x’ is
prime and return 1 otherwise if not prime then return 0.
void isEmirp( ) : reverses the given number and by invoking recursive function
isprime(int), check both original and reverse numbers are prime or not. Display the results with appropriate message.
Specify the class Emirp giving details of the constructor the functions int isprime(int), void isEmirp( ). Also define
the main( ) function to create an object and call the methods accordingly to check for Emirp number.

ANSWER :
// The following program is successfully compiled and executed
import [Link].*;
class Emirp
{
int n, rev, f ; // data members or variables of class
Emirp(int nn) // parameterized constructor
{ n = nn; // copy or assign values in parameter ‘nn’ to variable ‘n’
rev=0;
f = 2; // copy or assign fixed value ‘2’ to variable ‘f’
}//end of parameterized constructor
int isprime( int num) // function returns 1 if ‘num’ is prime else 0 by RECURSION
{
if( num == f )
return 1;
else if( num % f == 0 || num == 1)
return 0;
else
{ f++; // increase counter by 1
return( isprime( num )); //calling function isprime( ) within itself. It’s Recursion
}
}//end of recursive function isprime( )
void isEmirp( ) // function definition to check for EMIRP
{ int temp = n; // assign or copy ‘n’ to a variable ‘temp’
//now reversing the number stored in variable ‘temp’
while( temp > 0 ) // you may also write “while( temp != 0)”
{
rev = rev*10 + temp % 10; // extract digit from ‘temp’ and store in variable ‘rev’
temp = temp/10;
}//while loop closes here
int result1 = isprime( n ); // call recursive function by passing ‘n’ to ‘num’ to
//check ‘n’ is prime or not
f = 2; //re-assign value of variable ‘f’ to 2
int result2 = isprime( rev ); // call recursive function by passing reverse number in
// ‘rev’ to ‘num’ to check ‘rev’ is prime or not
if( result1 == 1 && result2 == 1 )
[Link]( n + " is Emirp number");
else
[Link]( n + " is not an Emirp number");
}//function isEmirp( ) ends here
//beginning of the main( ) function
public static void main( String args[ ] ) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter a number to check for emirp ");
int y=[Link]([Link]( ));
Emirp obj = new Emirp( y ); // making ‘obj’ object of class and passing ‘y’ to
// ‘nn’ i.e. to the parameterized constructor
obj. isEmirp( ); //calling function to check for Emirp and print the output
}//end of the main( ) function
}//class closes here
5 A happy number is a number in which the eventual sum of the square of the digits is equal to 1. 2012
ISC Recurssion Questions

Example 1 : 28 = (22) + (82) = 4+64= 68


68 = (62) + (82) = 36+64= 100
100 = (12) + (02) + (02) = 1+0+0= 1 Hence, 28 is a Happy number
Example 2 : 12 = (12) + (22) = 1+4= 5 Hence, 12 is not a Happy number
Design a class Happy to check if a given number is a happy number. Some of the members of the class are given below:
Class name Happy
Data members/instance variables:
n : to store an integer number.
Member functions/methods:
Happy( ) : constructor to assign 0 to n.
void getnum(int nn) : to assign the parameter value (nn) to n.
int sum_sq_digits(int x) : returns the sum of the square of the digits of the number
x,using the Recursive technique.
void ishappy( ) : checks if the given number is a happy number by calling the
recursive function sum_sq_digits(int) and displays the result with an appropriate message.
Specify the class Happy giving details of the constructor and functions void getnum( int), int sum_sq_digits( int) and
void ishappy( ). Also define the main( ) function to create an object and call the methods to check for happy number.

ANSWER:
// The following program is successfully compiled and executed
import [Link].*;
class Happy
{
int n; int sum;
Happy ( ) // this is default or non-parameterized constructor
{
n=0;
}
void getnum( int nn) // function to assign the 'nn' to 'n' as the number
{
n=nn;
}
int sum_sq_digits( int x ) // this function uses Recursion to get & return the sum
{
if( x>0 ) //this is base case or condition to stop recursion
{
int y = x % 10; // extract a digit from the number stored in 'x'
sum = sum + y * y; // add the square of 'y'
return ( sum_sq_digits(x/10) ); // here calling function within itself, this is Recursion
}//end if block
else
return (sum);
}//end of function sum_sq_digits( )
void ishappy ( ) // this function calls Recursive function to check for Happy number
{
sum=0; int num=n; //copy n to num
while( num>9 )
{
num=sum_sq_digits(num); // calling recursive function by passing num to x
sum=0;
}//while loop closes here
if (num = =1)
[Link](n + " IS A HAPPY NUMBER");
else
[Link]( n + " IS NOT A HAPPY NUMBER");
}//end of function ishappy( )
// beginning of main( ) function below
public static void main( String args[ ]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter a number " );
int a =[Link]([Link]());
Happy obj=new Happy( ); //making object of the class
obj. getnum(a); // calling function by passing 'a' to 'nn'
obj. ishappy( ); // calling function to check that the number is Happy no. or not
}//end of main( ) function
}//class closes here
6 A class DeciOct has been defined to convert a decimal number into its equivalent octal number. Some of the members of 2011
the class are given below.
Class name : DeciOct
Data members / instance variables:
n : stores the decimal number
oct : stores the octal equivalent number
Member functions :
DeciOct( ) : constructor to initialize the data members n=0, oct=0
ISC Recurssion Questions
void getnum( int nn) : assign nn to n
void deci_oct ( ) : calculates the octal equivalent of ‘n’ and stores it in oct using the Recursive
Technique
void show( ): displays the decimal number ‘n’, calls the function deci_oct( ) and displays its octal
equivalent.
(a) Specify the class DeciOct, giving details of the constructor( ), void getnum(int ), void deci_oct( ), void show
( ). Also define a main( ) function to create an object and call the functions accordingly to enable the task.
(b) State any two disadvantages of using recursion
import [Link].*;
class DecOct
{
public int n, oct;
public DecOct( )
{
n = 0;
oct = 0;
}
public void getnum( )
{
Scanner ob = new Scanner([Link]);
[Link]("Enter an integer number to convert");
n = [Link]( );
}
public void show( )
{
decioct( n );
[Link]("Octal value of number " + n + " is " + oct);
}
public void decioct( int p)
{ int a;
if(p>0)
{
a =p % 8;
decioct( p / 8 );
oct = oct * 10 + a;
}
}
public static void main(String arg[ ])
{
DecOct obj = new DecOct( );
[Link]( );
[Link]( );
}
}

7 Design a class Change to perform string related operations. The details of the class are given below: 2010
Class name : Change
Data Members / instance variables:
str : stores the word
newstr : stores the changed word
len : store the length of the word
Member functions:
Change( ) : default constructor
void inputword( ) : to accept a word
char caseconvert(char ch) : converts the case of the character and returns it
void recchange(int) : extracts characters using Recursive Technique and changes its case using
caseconvert( ) and forms a new word
void display( ) : display both the words

(a) Specify the class Change, giving details of the constructor( ), member functions void inputword( ), char
caseconvert(char ch), void recchange(int) and void display( ). Define the main( ) function to create an object and
call the functions accordingly to enable the above change in the given word.
(b) Differentiate an infinite and a finite recursion.

import [Link].*;
class Change
{
Scanner ob = new Scanner([Link]);
String str, newstr;
int len;
public Change()
{
len=0;
newstr="";
}
void inputword()
{
ISC Recurssion Questions
[Link]("Enter word for case conversion");
str= [Link]( );
}
char caseconvert(char ch)
{
if([Link](ch)) ch=[Link](ch);
else if([Link](ch)) ch=[Link](ch);
return ch;
}
void recchange(int x)
{
if(x>=0)
{
recchange(x-1);
newstr=newstr + caseconvert([Link](x));
}
}
void display()
{
len=[Link]();
recchange(len-1);
[Link](newstr);
}
public static void main(String arg[]) throws IOException
{
Change object=new Change();
[Link]();
[Link]();
}
}
8 Class Binary contains an array of n integers (n<=100) that are already arranged in ascending order. The subscripts of the array 2009
elements vary from 0 to n-1. The data members and member function of the class Binary are given below:
Class name : Binary
Data members/Instance variables :
A[ ] : integer array of 100 elements
n : size of the array
l : location of the lower bound
u : location of the upper bound
Member functions/methods :
Binary( int nn) : constructor to initialize the size n=nn and the other
instance variables
void readdata( ) : to fill the elements of the array in ascending order
int binary_search(int v ) : returns the location of the value (v) to be searched in the list by
binary search method using the Recursive Technique. The
function returns -1 if the number is not present in the given list.
(a) Specify the class Binary giving the details of the constructor, void readdata( ), and int binary_search(int ). You need
not write the main function.
(b) State the Base Case in the recursive function binary_search( ).
(c) What are the drawbacks of using the recursive technique?
import [Link].*;
class Binary
{
Scanner ob = new Scanner([Link]);
public int A[ ]=new int[100],n,l,u,c;
public Binary(int nn)
{ n=nn;
l=0;
u=n-1;
}
public void readdata( )
{
[Link]("Enter the elements in ascending order");
for(int i=0;i<n;i++)
{ [Link]("Enter the element");
A[i]= [Link]( );
}
[Link]("Enter the element to be searched");
c= [Link]( );
int a=binary_search(c);
[Link](a);
}
public int binary_search(int d)
{ int mid=(l+u)/2;
if(d==A[mid]) return(mid+1);
if(l>u) return(-1);
if(d!=A[mid])
{ if(d>A[mid]) l=mid+1;
if(d<A[mid]) u=mid-1;
ISC Recurssion Questions
}
return binary_search(d);
}
public static void main(String args[])throws IOException
{
[Link]("Enter the number of elements in array");
int e= [Link]( );
Binary obj=new Binary(e);
[Link]();
}
}

9 A class Revstr defines a recursive function to reverse a string and check whether it is a Palindrome. The details of the class 2007
are given below:
Class name : Revstr
Data members/Instance variables :
Str : stores the string
Revst : stores the reverse of the string
Member functions/methods :
void getStr( ) : to accept the string
void recReverse( int ) : to reverse the string using the Recursive Technique
void check( ) : to display the original string, its reverse and whether the string is a Palindrome or not.
Specify the class Revstr giving the details of the functions void getStr( ), void recReverse(int) and void check( ). The main
function need not be written.

class recur_revstring
{
Scanner ob = new Scanner([Link]);
public String str,revst;
public int len;
public recur_revstring( )
{
str ="";
revst ="";
}
public void input( )
{
str = [Link]( );
}
public void check( )
{
len=[Link]( );
revstring(0);
[Link](str + " "+ revst);
if([Link](revst) ) [Link]("String is Palindrome");
else [Link]("String is not a Palindrome");
}
public void revstring(int n)
{ if(n<len)
{
char ch=[Link](n);
revstring(n+1);
revst=revst+ch;
}
}
public static void main(String arg[]) throws IOException
{
recur_revstring obj = new recur_revstring( );
[Link]( );
[Link]( );
}
} 2008
10 Class Convert has been defined to express digits of an integer in words.
The details of the class are given below:
Class name : Convert
Data members:
n : integer whose digits are to be expressed in words.
Member functions:
Convert( ) : constructor to assign 0 to n.
void inpnum( ) : to accept the value of n.
void extdigit(int) : to extract the digits of n using the Recursive technique.
void num_to_words(int ) : to display the digits of an integer n in words.

Specify the class Convert, giving details of the constructor and the functions, void inpnum( ), void extdigit(int) and void
num_to_words( ). The main function need not be written.
A class dec_Bin has been defined to convert a decimal number into its equivalent binary number. Some of the members of 2007 R
the class are given below:
Class name : dec_Bin
ISC Recurssion Questions
Data members:
n : integer to be converted to its binary equivalent.
s : binary equivalent number.
i : incremental value of power.
Member functions:
dec_Bin( ) : constructor to assign initial value to the data members.
void getdata( ) : to accept the value of n.
void recursive(int) : to calculate the binary equivalent of ‘n’ using the Recursive technique.
void putdata( ) : to display the decimal number ‘n’ and its binary equivalent.

(a) Specify the class dec_Bin, giving details of the constructor and the functions, void getdata( ), void recursive(int) and
void putdata( ).
(b) Give any two differences between the recursive and iteration process.
import [Link].*;
class dec_bin
{
Scanner br=new Scanner([Link]);
public int n, z, i;
public dec_bin ( )
{
i = 0;
z = 0;
}
public void getdata( )
{
[Link]("Enter an integer number to convert");
n = [Link]( );
}
public void putdata( )
{
[Link]("Binary value of number " + n + " is ");
recursive(n);
[Link]( z );
}
public void recursive(int p)
{ int a;
if(p>0)
{
a =p % 2;
z = z + (int) [Link](10, i) * a;
i++;
recursive( p / 2 );
}
}
public static void main(String arg[ ])
{
dec_bin obj = new dec_bin ( );
[Link]( );
[Link]( );
}
}

11 Class Hifact has been defined to to find the HCF of two numbers using the recursive technique. This HCF is used to find 2006
the LCM of the two numbers. Some members of the class are given below :
Class name : Hifact
Data members:
a, b, hcf, lcm : integers
Member functions:
Hifact( ) : constructor to assign initial values to the data members.
void getdata( ) : to input values of a and b.
void change( ) : to swap a and b if a > b
int rechef(int, int) : to find hcf using the Recursive technique.
int fn_lcm(int, int, int) : to find lcm using a, b, and hcf
void result( ) : to invoke rechef( ) and fn_lcm( ) and to print lcm, hcf of two
numbers, a and b.

Specify the class Hifact, giving details of the constructor and the functions, void getdata( ), void change( ), int rechef( )
and int fn_lcm( ). Write the main function and find the hcf and lcm of any two integers a and b.
import [Link].*;
class Hifact
{
Scanner ob = new Scanner([Link]);
int a,b,hcf,lcm;
public Hifact( ) // constructor
{
a=0;
b=0;
ISC Recurssion Questions
}
public void getdata( ) // entering the value of A and B
{
[Link]("Enter the values of a and b");
a= [Link]( );
b= [Link]( );
}
public void change( ) // reversing if a>b
{
if(a>b)
{
int temp=a;
a=b;
b=temp;
}
}
public void result( ) // calculating hcf and lcm
{
hcf=rechef(a,b);
lcm=fn_lcm(a,b,hcf);
[Link]("The hcf and lcm of a and b are "+hcf+" and "+lcm);
}
public int rechef(int a,int b) //finding hcf using recursion
{
if(b%a==0) return a;
else return rechef(b%a, a);
}
public int fn_lcm(int a,int b,int c) // finding lcm
{
return (a*b)/c;
}
public static void main(String args[])
{
Hifact ob=new Hifact( );
[Link]( );
[Link]( );
[Link]( );
}
}

12 A class recursion has been defined to find the Fibonacci series upto a limit. Some of the members of the class are given 2005
below:
Class name: : recursion
Data members/ instance variables :
a, b, c, limit : integer type
Member functions/methods
recursion( ) : constructor to assign a, b, c with appropriate values.
void input( ) : to accept the limit of the series
int fib(int n) : to return the nth Fibonacci term using recursive technique
void generate_fibseries( ) : to generate fibonacci series upto the given limit

(a) Specify the class recursion, giving the details of the constructor, int fib( ), void input( ), void generate_fibseries(
).
(b) Why recursive functions result into slower execution of the program?
import [Link].*;
class recur_fibonacci
{
int n, i;
public recur_fibonacci ( )
{
n=0;
}
public void input( ) throws IOException
{
BufferedReader b=new BufferedReader(new InputStreamReader([Link]));
[Link]("enter a number");
n=[Link]([Link]( ));
}
public int fibo(int n)
{
if(n==0) return(0);
if(n==1) return(1);
return (fibo(n-2)+fibo(n-1));
}
public void display( )
{
ISC Recurssion Questions
for(i=0;i<=n;i++)
{
int e=fibo(i);
[Link]((i+1) + " Term is = "+e);
}
}
public static void main(String args[ ])throws IOException
{
recur_fibonacci obj=new recur_fibonacci ( );
[Link]( );
[Link]( );
}
}

13 A class series has been defined to compute the sum of the following series:
1 + 1+1 + 1+1+2 + 1+1+2+3 + 1+1+2+3+5 +…………. + 1+1+2+3+5+8….
21 22 23 24 25 2n
Some of the members and functions of the class series are :
Class name : : series
Data members:
int n : to store the limit of the series
double sum : to store the sum of the series
Member functions:
series( ) : constructor to initialize variables
long fib(long x) : returns the sum of the Fibonacci series upto x terms
long power(long x) : return the value of 2x i.e. 2 raised to the power of x using recursive technique
void sumseries( ) : calculates and prints the sum of the given series

Specify the class series giving details of the constructor and functions long fib(long x), long power(long x) and void
sumseries( ).

import [Link].*;
class series
{
int n;
double sum;
public series( )
{
n=0;
sum=0.0;
}
public void input( ) throws IOException
{
BufferedReader b=new BufferedReader( new InputStreamReader([Link] ));
n=[Link]([Link]( ));
sumseries( );
}
public int fib(int n)
{
if(n==0) return(0);
if(n==1) return(1);
return fib(n-2)+fib(n-1);
}
public long power(long x)
{
if(x==1) return(2);
else return 2*power(x-1);
}
public void sumseries( )
{
for(int i=1;i<=n;i++)
{
sum = sum + (double) fib(i)/power(i);
}
[Link]("The sum="+sum);
}
public static void main(String args[ ])throws IOException
{
series obj=new series( );
[Link]( );
}
}

14 A class sumseries has been defined to compute the sum of the following series:
1! - 2! + 3! - 4! + 5! - …………. . n!
X2 X3 X4 X5 X6 Xn+1
ISC Recurssion Questions

Some of the members and functions of the class series are :


Class name : : series
Data members:
int X : to store value of X
int n : to store the limit of the series
double sum : to store the sum of the series
Member functions:
sumseries( ) : constructor to initialize variables
void input( ) : accepts values of X and n
long factorial(long n) : calculate and returns n! using recursive technique
n! = n * (n-1) * (n-2) * (n-3) * …… * 1
long power(int a, int b) : return the value of ab i.e. a raised to the power of b using
recursive technique
double term(int p. int q) : returns the value of factorial( ) / power( ) function
double calsum( ) : calculates the sum of the given series
void display( ) : displays the value of sum data member.

Specify the class sumseries giving details of the constructor and functions long factorial (long n), long power(int, int),
double term(int, int), double calcum( ) and void display( ).
import [Link].*;
class sumseries
{
public int x,n;
public double sum;
public sumseries() // constructor
{
x=0;n=0;sum=0;
}
public static void main(String args[]) // main function
{
sumseries ob=new sumseries();
[Link]();
[Link]();
}
public void input() // entering the limit and x
{
[Link]("Enter the limit");
Scanner ab=new Scanner([Link]);
n=[Link]();
[Link]("Enter the limit");
x=[Link]();
}
public long factorial(long n) // calculating factorial using recursion
{
if(n==1)
return 1;
else
return n*factorial(n-1);
}
public long power(int a,int b) // calculating a to power b using recursion
{
if(b==1)
return a;
else
return a*power(a,b-1);
}
public double term(int p,int q) // calculating a term of the series
{
return (factorial(p)*1.00)/(power(x,q)*1.00);
}
public double calsum() // calculating the sum of the series
{
int sg=1;
for(int i=1;i<=n;i++)
{
sum+=term(i,i+1)*sg;sg*=-1;
}
return sum;
}
public void display() // displaying the sum
{
[Link]("The sum of the seies is "+calsum());
}
}
15 The Combination function C(n , k ) gives the number of different (unordered ) K – elements Subsets that can be found in a
given set of n elements. The function can be computed from the formula:
C (n, k) = n!____
k! (n - k)!
Design a class Combination to implement this formula. Some of the data members and member functions are given below.
ISC Recurssion Questions
Class name : Combination
Data members / instance variables :
n : integer number
k : integer number
Member functions :
Combination ( ) : to initialize the data members n = 0 and k = 0
void read ( ) : to accept the value of the data members
int fact(int) : return the factorial of a number using Recursion Technique.
void compute( ) : calculate the combination value
void display( ) : to show the result

Specify the class Combination, giving details of the constructor and member functions void read( ), int fact(int), void
compute( ) and void display( ) with the main( ) function to create an object and call the member function according to enable
the task.
import [Link].*;
class Combination
{
int x, k, c;
public Combination( )
{
x=0;
k=0;
}
public void input( ) throws IOException
{
BufferedReader b=new BufferedReader(new InputStreamReader([Link]));
[Link]("enter a number");
x=[Link]([Link]());
[Link]("enter a number");
k=[Link]([Link]());
}
public int fact(int a)
{
if(a==1) return(1);
else return(a*fact(a-1));
}
public void compute( )
{
c=fact(x+k)/(fact(x)*fact(k));
}
public void display( )
{
[Link]("Value is "+c);
}
public static void main(String args[ ]) throws IOException
{
Combination obj=new Combination( );
[Link]( );
[Link]( );
[Link]( );
}
}

You might also like