0% found this document useful (0 votes)
27 views17 pages

Giu 2478 61 14620 2024-01-07T22 10 06

The document contains a series of programming exercises for an Introduction to Computer Science course, focusing on recursive methods in Java. Each exercise includes a description, a sample implementation, and a main method for testing. Topics covered include countdowns, power calculations, natural logarithms, multiplication, division, modulus, sum of digits, number of digits, prime checking, cube numbers, and binomial coefficients.

Uploaded by

a6900710
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)
27 views17 pages

Giu 2478 61 14620 2024-01-07T22 10 06

The document contains a series of programming exercises for an Introduction to Computer Science course, focusing on recursive methods in Java. Each exercise includes a description, a sample implementation, and a main method for testing. Topics covered include countdowns, power calculations, natural logarithms, multiplication, division, modulus, sum of digits, number of digits, prime checking, cube numbers, and binomial coefficients.

Uploaded by

a6900710
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
You are on page 1/ 17

German International University of Applied Science

Informatics and Computer Science


Prof. Dr. Slim Abdennadher

Introduction to Computer Science, Winter 2023


Practice Assignment 10

Exercise 10-1 Blast Off


Write a recursive method countdown that takes a single integer as a parameter from the user and prints
the numbers from n until 1 and then prints ”Blastoff!”. If the parameter is zero, it prints only the word
”Blastoff!”
For example if the user will enter 6 then the program should output:

6
5
4
3
2
1
Blastoff!

Solution:
import j a v a . u t i l . ∗ ;
public c l a s s Countdown {
public s t a t i c void countdown ( int n ) {
i f ( n == 0 ) {
System . out . p r i n t l n ( " B l a s t o f f ! " ) ;
} else {
System . out . p r i n t l n ( n ) ;
countdown ( n−1) ;
}
}
public s t a t i c void main ( S t r i n g [ ] a r g s )
{
Scanner s c = new Scanner ( System . i n ) ;
System . out . p r i n t l n ( " P l e a s e ␣ e n t e r ␣ a ␣number : ␣ " ) ;
int i n p u t = s c . n e x t I n t ( ) ;
countdown ( i n p u t ) ;
}
}

Exercise 10-2 Power


Consider the evaluation of xn , where n is a non-negative integer. Write a recursive method powerRec to
calculate xn .
Write a main method to test your method.

Solution:
public s t a t i c int PowerRec ( int x , int n ) {
i f ( n == 0 )

1
return 1 ;
else {
i f ( n%2 == 0 )
return ( PowerRec ( x , n / 2 ) ∗ PowerRec ( x , n / 2 ) ) ;
else
return ( x ∗ PowerRec ( x , n−1) ) ;
}
}

Exercise 10-3 Natural Logarithm


Write a recursive method constantRec to calculate the value of the mathematical constant e which is
defined as:

1 1 1 1 1
e(n) = + + + + ... +
0! 1! 2! 3! n!

Implement first a recursive method factorial, where f actorial(n) = n!.


Write a main method to test your method.

Solution:
public c l a s s ConsR {
public s t a t i c double c o n s t a n t R e c ( int n ) {
i f ( n == 0 )
return 1 . 0 ;
else
return ( 1 . 0 / f a c t ( n ) ) + c o n s t a n t R e c ( n−1) ;
}

public s t a t i c double f a c t ( double n ) {


i f ( n==0)
return 1 ;
else {
return n ∗ f a c t ( n−1) ;
}
}
public s t a t i c void main ( S t r i n g [ ] a r g s ) {
System . out . p r i n t l n ( c o n s t a n t R e c ( 8 ) ) ;
System . out . p r i n t l n ( c o n s t a n t R e c ( 1 5 ) ) ;
}
}

Exercise 10-4 MultilplyRec


Write a recursive method multiplyRec that perform the multiplication of two numbers.

f (x, y) = x ∗ y

Your method will use only the addition and subtraction operators.
Write a main method to test your method.
Hint:

x ∗ y = x + x + ... + x
| {z }
y times

2
Solution:
import j a v a . u t i l . ∗ ;
public c l a s s M u lt i p ly R e c {
public s t a t i c int M u lt i p ly R e c ( int num1 , int num2) {
i f (num2 == 0 )
return 0 ;
else
return (num1 + M ul t i pl y R ec (num1 , num2−1) ) ;
}
public s t a t i c void main ( S t r i n g a r g s [ ] ) {
Scanner s c = new Scanner ( System . i n ) ;
System . out . p r i n t ( " Enter ␣ t h e ␣ f i r s t ␣num : ␣ " ) ;
int numA = s c . n e x t I n t ( ) ;
System . out . p r i n t ( " Enter ␣ t h e ␣ s e c o n d ␣num : " ) ;
int numB = s c . n e x t I n t ( ) ;
System . out . p r i n t l n ( "The␣ p r o d u c t ␣ i s ␣ " + Mu l t i pl y R ec (numA,
numB) ) ;
}
}

Exercise 10-5 Division


Write a recursive Java method divideRec that perform the integer division operation of two numbers. If
y is a negative number, an error message has to be displayed.

x
f (x, y) =
y

DO NOT USE THE JAVA PREDEFINED OPERATOR /.


Hint:

: if x < y

x 0
= x−y
y 1+ y : Otherwise

Write a main method to test your method.

Solution:
public s t a t i c int d i v i d e R e c ( int x , int y ) {
i f ( y <= 0 )
return −1;
else i f (x < y)
return 0 ;
else
return 1 + d i v i d e R e c ( x−y , y ) ;
}

Exercise 10-6 Modulus


Write a recursive Java method ModulusRec that perform the modulus operation of two integers. If y is a
negative number, an error message has to be displayed.

f (x, y) = x%y

DO NOT USE THE JAVA PREDEFINED OPERATOR %.

3
Hint:

: if x = 0

 0
x%y = x : if x < y
(x − y)%y : Otherwise

Write a main method to test your method.

Solution:
public c l a s s ModulusRec {
public s t a t i c int modRec ( int x , int y ) {
i f ( x == 0 )
return 0 ;
else i f (x < y)
return x ;
else
return modRec ( x−y , y ) ;
}
public s t a t i c void main ( S t r i n g [ ] a r g s ) {
System . out . p r i n t l n ( modRec ( 7 , 2 ) ) ; // where 7%2=1
System . out . p r i n t l n ( modRec ( 0 , 2 ) ) ; // where 0%2=0
System . out . p r i n t l n ( modRec ( 3 , 5 ) ) ; // where 3%5=3
System . out . p r i n t l n ( modRec ( 6 , 2 ) ) ; // where 6%2=0
}
}

Exercise 10-7 Sum of Digits


Write a recursive method to determine the sum of the digits of an integer. For example, the sum of digits
of 51624 is 5 + 1 + 6 + 2 + 4 = 18.

Solution:
import j a v a . u t i l . ∗ ;
public c l a s s SumOfDigits {
public s t a t i c int add ( int num)
{
i f (num < 1 0 )
return num ;
else
return ( ( num % 1 0 ) + add (num / 1 0 ) ) ;
}
public s t a t i c void main ( S t r i n g [ ] a r g s ) {
Scanner s c = new Scanner ( System . i n ) ;
System . out . p r i n t l n ( " P l e a s e ␣ e n t e r ␣ a ␣number : ␣ " ) ;
int i n p u t = s c . n e x t I n t ( ) ;
System . out . p r i n t l n ( "The␣sum␣ o f ␣ t h e ␣ d i g i t s ␣ o f ␣ " + i n p u t + " ␣
i s ␣"
+ add ( i n p u t ) ) ;
}
}

Exercise 10-8 Number of Digits


Write a recursive Java method numberDigitsRec, which given an integer, returns its number of digits.
For example the call numberDigitsRec(12312) will return 5.

4
Solution:
public s t a t i c int numberDigitsRec ( int x ) {
i f ( x%10 == x )
return 1 ;
else
return numberDigitsRec ( x / 1 0 ) + 1 ;
}

Exercise 10-9 Prime


A prime number is an integer that cannot be divided by any integer other than one and itself. For example,
7 is prime because its only divisors are 1 and 7. The integer 8 is not prime because its divisors are 1, 2,
4, and 8.
Another way to define prime is:

prime(N) = prime(N, N-1)

prime(N, 1) = true

prime(N, D) = false if D divides N


prime(N, D-1) otherwise

For example,

prime(4) = prime(4,3)
prime(4,3) = prime(4,2)
prime(4,2) = false

Another example,

prime(7) = prime(7,6)
prime(7,6) = prime(7,5)
prime(7,5) = prime(7,4)
prime(7,4) = prime(7,3)
prime(7,3) = prime(7,2)
prime(7,1) = true

Translate the math-like definition of prime into two Java methods that return boolean. Use the % operator
to test divisibility. Put your method into a class, write a testing class, and test your program. (Look at
Triangle.java in this assignment.)

Solution:
import j a v a . u t i l . ∗ ;
public c l a s s Prime {
public s t a t i c boolean Prime ( int n ) {
i f ( n == 1 )
return true ;
else
return prime ( n , n−1) ;
}

public s t a t i c boolean prime ( int n , int d ) {


i f ( d == 1 )
return true ;

5
e l s e i f ( n%d == 0 )
return f a l s e ;
e l s e return prime ( n , d−1) ;
}

public s t a t i c void main ( S t r i n g [ ] a r g s ) {


Scanner s c = new Scanner ( System . i n ) ;
System . out . p r i n t l n ( " P l e a s e ␣ e n t e r ␣ a ␣ p o s i t i v e ␣number" ) ;
int n = s c . n e x t I n t ( ) ;
boolean r e s u l t = prime ( n ) ;
if ( result )
System . out . p r i n t l n ( "The␣number␣ " + n + " ␣ i s ␣ prime . "
);
else
System . out . p r i n t l n ( "The␣number␣ " + n + " ␣ i s ␣ not ␣
prime . " ) ;
}
}

Exercise 10-10 Cube numbers


Write a program that implements this definition of cube numbers, where N is an integer entered by the
user.

cube(1) = 1
cube(N) = cube(N-1) + 3(square(N)) - 3N + 1

Implement the square() method using this definition

(N − 1)2 = N 2 − 2N + 1

Solution:
import j a v a . u t i l . ∗ ;
public c l a s s Cube {
public s t a t i c int cube ( int n ) {
i f ( n == 1 )
return n ;
else
return cube ( n−1) + ( 3 ∗ s q u a r e ( n ) ) − ( 3 ∗ n ) + 1 ;
}
public s t a t i c int s q u a r e ( int n ) {
i f ( n == 1 )
return n ;
else
return s q u a r e ( n − 1 ) + ( 2 ∗ n ) − 1 ;
}

public s t a t i c void main ( S t r i n g a r g s [ ] ) {


Scanner s c = new Scanner ( System . i n ) ;
System . out . p r i n t l n ( " P l e a s e ␣ e n t e r ␣ a ␣number : ␣ " ) ;
int i n p u t = s c . n e x t I n t ( ) ;
System . out . p r i n t l n ( "The␣ cube ␣number␣ o f ␣ " + i n p u t + " ␣ i s ␣␣ "
+ cube ( i n p u t ) ) ;
}
}

6
Exercise 10-11 Binomial Coefficient
The binomial coefficient nk is the number of ways of picking k unordered outcomes from n possibilities,


also known as a combination or combinatorial number.


The binomial coefficient is defined recursively as follows:

if k = 0

   1 :
n
= 1 : if n = k
k  n−1
+ n−1

: otherwise
k k−1

Write a recursive method to calculate the binomial coefficient. Make sure that n is less than k.
Write a main method that will allow the user to enter the actual parameters of the binomial coefficient
method. Use either Scanner class or the command line arguments as input mechanism.
public s t a t i c void main ( S t r i n g [ ] a r g s ) {
Scanner s c = new Scanner ( System . i n ) ;
....

Solution:
public c l a s s Binom {
public s t a t i c long c h o o s e ( int n , int k )
{
long answer ; // Hold t h e answer
i f ( k == 0 | | n == k )
answer = 1 ;
else
answer = c h o o s e ( n−1, k ) + c h o o s e ( n−1, k−1) ;
return answer ;
}

public s t a t i c void main ( S t r i n g a r g s [ ] ) {


Scanner s c = new Scanner ( System . i n ) ;
int n = s c . n e x t I n t ( ) ; // s i z e o f t h e s e t
int k = s c . n e x t I n t ( ) ; // number o f o b j e c t s
System . out . p r i n t l n ( " There ␣ a r e ␣ " + c h o o s e ( n , k ) + " ␣ ways ␣ t o ␣
choose ␣"
+ k + "␣
objects ␣
out ␣ o f ␣ "
+ n) ;
}
}

Exercise 10-12 CountRec


Write a recursive method named countRec that accepts two arguments: a String value, and a char
value. Your method is to return the total number of times the character appears inside of the string.

Solution:
public c l a s s Count {
public s t a t i c int count ( S t r i n g x , char c ) {
i f ( x . l e n g t h ( ) == 0 )
return 0 ;
e l s e i f ( x . charAt ( 0 ) == c )
return count ( x . s u b s t r i n g ( 1 ) , c ) + 1 ;

7
else
return count ( x . s u b s t r i n g ( 1 ) , c) ;
}
public s t a t i c void main ( S t r i n g a r g s [ ] ) {
System . out . p r i n t l n ( count ( " H e l l o " , ’l ’) ); // displays 2
System . out . p r i n t l n ( count ( " H e l l o " , ’o ’ ) ); // displays 1
System . out . p r i n t l n ( count ( " H e l l o " , ’H ’ ) ); // displays 1
System . out . p r i n t l n ( count ( " H e l l o " , ’h ’ ) ); // displays 0
}
}

Exercise 10-13 Reverse


Consider reversing the characters in a string. Write a recursive Java method reverseRec that returns a
new string with the same characters of the original string, but in reversed order.
Think about the base case and recursive case:

• Base case: ReverseRec("") => ""


• Recursive case:

reverse("ABCDE") => "E" + ReverseRec("ABCD") => ...... => "EDCBA"

Hint: In addition to the methods charAt and length, use the predefined method substring(). For
example if we have a string String s = "CSEN202", then s.substring(1) returns "SEN202", i.e. the
string s without the first character.
Write a main method to test your method.

Solution:
public c l a s s R e v e r s e {
public s t a t i c S t r i n g r e v e r s e R e c ( S t r i n g s ) {
i f ( s . l e n g t h ( ) <= 1 )
return s ; // 1 or 0 c h a r a c t e r s t r i n g i s
i t s own r e v e r s e
else
return r e v e r s e R e c ( s . s u b s t r i n g ( 1 ) ) + s . charAt ( 0 ) ;
}
public s t a t i c void main ( S t r i n g [ ] a r g s ) {
String x = (" abcdefghij ") ; // Sample s t r i n g
System . out . p r i n t l n ( r e v e r s e R e c ( x ) ) ;
}
}

Exercise 10-14 Palindrome


Write a recursive method palindrome that takes a single string as a parameter from the user and returns
whether the string is palindrome or not.

Solution:
import j a v a . u t i l . Scanner ;
public c l a s s P a l i R e c {

public s t a t i c void main ( S t r i n g [ ] a r g s )


{

8
Scanner s c = new Scanner ( System . i n ) ;
System . out . p r i n t l n ( " P l e a s e ␣ e n t e r ␣ a ␣word␣ t o ␣ be ␣ checked ␣ f o r ␣
palindrome " ) ;
String x = sc . nextLine ( ) ;
System . out . p r i n t l n ( p a l i n d r o m e ( x ) ) ;
}

public s t a t i c boolean p a l i n d r o m e ( S t r i n g x )
{
i f ( x . l e n g t h ( )==0 | | x . l e n g t h ( )==1 )
return true ;
i f ( x . charAt ( 0 ) == x . charAt ( x . l e n g t h ( ) −1) )
return p a l i n d r o m e ( x . s u b s t r i n g ( 1 , x . l e n g t h ( ) −1) ) ;

return f a l s e ;
}

Exercise 10-15 Replace


To be discussed in Tutorials
Write a recursive method replace that takes two arguments: String and char and replaces each occur-
rence of the character with a ’*’

Solution:
public c l a s s R ep l ac e {
public s t a t i c S t r i n g r e p l a c e ( S t r i n g s , char c ) {
i f ( s . l e n g t h ( ) == 0 ) {
return " " ;
} e l s e i f ( s . charAt ( 0 ) != c ) {
return s . charAt ( 0 ) + r e p l a c e ( s . s u b s t r i n g ( 1 ) , c ) ;
} else {
return "∗ " + r e p l a c e ( s . s u b s t r i n g ( 1 ) , c ) ;
}
}
public s t a t i c void main ( S t r i n g [ ] a r g s ) {
System . out . p r i n t l n ( r e p l a c e ( "Computer␣ S c i e n c e " , ’ e ’ ) ) ;
}
}

Exercise 10-16 Eliminate


Write a recursive method eliminate that takes a String and a char and deletes each occurrence of this
character from the string.

Solution:
public s t a t i c S t r i n g e l i m ( S t r i n g s , char c )
{
i f ( s . l e n g t h ( ) == 0 )
return " " ;
e l s e i f ( s . charAt ( 0 ) != c )
return s . charAt ( 0 ) + e l i m ( s . s u b s t r i n g ( 1 ) , c ) ;
else
return e l i m ( s . s u b s t r i n g ( 1 ) , c ) ;

9
}

Exercise 10-17 Recursion Tracing 1


Give the following program:
public s t a t i c void mystery1 ( int a , int b ) {
i f ( a <= b ) {
int m =(a + b ) / 2 ;
System . out . p r i n t (m + " ␣ " ) ;
mystery1 ( a , m − 1 ) ;
mystery1 (m+1, b ) ;
}
}

What is the output of the main method below? Justify your answer with a tracing table.
public s t a t i c void main ( S t r i n g [ ] a r g s ) {
int n = 6 ;
mystery1 ( 0 , n ) ;
}

Solution:
3 1 0 2 5 4 6

Exercise 10-18 Recursion Tracing 2


To be discussed in Tutorials
Give the following program:
public s t a t i c void mystery ( S t r i n g p r e f i x , S t r i n g remaining , int k ) {
i f ( k == 0 ) {
System . out . p r i n t l n ( p r e f i x ) ;
return ;
}
i f ( r e m a i n i n g . l e n g t h ( ) == 0 ) return ;
mystery ( p r e f i x + r e m a i n i n g . charAt ( 0 ) , r e m a i n i n g . s u b s t r i n g ( 1 ) , k−1) ;
mystery ( p r e f i x , r e m a i n i n g . s u b s t r i n g ( 1 ) , k ) ;
}

a) What is the value returned by the following invocation? Trace your program. mystery("", "CSEN", 3)

Solution:
CSE
CSN
CEN
SEN
b) What does the above method do? Give an concise verbal description of how the value returned by
mystery("", s, k) is related to the values of the parameters s and k.

Solution:
The method prints out all subsequences of s of length k.

10
Exercise 10-19 Search
Write a recursive method search() to search for a char inside a String and returns its position inside
the String. The method should returns -1 if the char is not in the String.
Use the following main method to test your program:
public s t a t i c void main ( S t r i n g [ ] a r g s ) {
System . out . p r i n t l n ( s e a r c h ( " example " , ’ a ’ ) ) ;
}

Hint:

• “Hello”.substring(1) returns “ello”.


• “Hello”.substring(1,4) returns “ell”.
• “Hello”.substring(0,s.length()-1) returns “Hell”.

Solution:
public s t a t i c int s e a r c h ( S t r i n g s , char c )
{
i f ( s . l e n g t h ( ) ==0)
return −1;
e l s e i f ( s . charAt ( s . l e n g t h ( ) −1) == c )
return s . l e n g t h ( ) − 1 ;
else
return s e a r c h ( s . s u b s t r i n g ( 0 , s . l e n g t h ( ) −1) , c ) ;
}

Exercise 10-20 Put At Front - Final Spring 2013


To be solved in labs
Write a recursive method putAtFront that takes two parameters, a string s and a character c. The
method returns a string with all occurrences of c placed at the front of the string and all other characters
afterwards, in the same order they appear in the input string. If c does not exist, then the output string
is the same as s. If c is at the beginning of s, and it does not appear in s any more time, then the output
string is also the same as s.
The following list illustrates 4 different calls and the correct return value from calling the method each
time.

Call: putAtFront("sce", ’c’);


Return: cse
// note how c is at the front of the returned
// string and the remaining characters afterwards.
Call: putAtFront("static", ’t’);
Return: ttsaic
// here t appears twice in input string s.
// In the returned string, both are at front,
// and the remaining afterwards.
Call: putAtFront("banana", ’a’);
Return: aaabnn
Call: putAtFront("java", ’j’);
Return: java
Call: putAtFront("ALL", ’L’);
Return: LLA

Solution:

11
import j a v a . u t i l . Scanner ;

public c l a s s PutAtFront {

public s t a t i c void main ( S t r i n g [ ] a r g s ) {


Scanner s c = new Scanner ( System . i n ) ;
System . out . p r i n t l n ( " P l e a s e ␣ e n t e r ␣ ␣ t h e ␣ s t r i n g : ␣ " ) ;
String s = sc . nextLine () ;
System . out . p r i n t l n ( " P l e a s e ␣ e n t e r ␣ ␣ t h e ␣ c h a r a c t e r : ␣ " ) ;
char c = s c . n e x t L i n e ( ) . charAt ( 0 ) ;
System . out . p r i n t l n (
"The␣ g e n e r a t e d ␣ s t r i n g ␣ with ␣ t h e ␣ o c c u r e n c e s ␣ o f ␣ "
+ c + " ␣ put ␣ a t ␣ f r o n t ␣ i s : ␣ " + putAtFront ( s , c ) ) ;
}

public s t a t i c S t r i n g putAtFront ( S t r i n g s , char c ) {


i f ( s . l e n g t h ( ) == 0 )
return s ;

else {
i f ( s . charAt ( s . l e n g t h ( ) − 1 ) == c ) {
return c + putAtFront ( s . s u b s t r i n g ( 0 ,
s . length ( ) − 1) , c ) ;
}
else {
return putAtFront ( s . s u b s t r i n g ( 0 ,
s . l e n g t h ( ) − 1 ) , c ) + s . charAt ( s . l e n g t h ( ) −
1) ;
}
}
}
}

Exercise 10-21 PerfectRec


A positive integer is said to be perfect if the sum of its factors (excluding the integer itself) is that integer.
For example, 6 is perfect, since the numbers that divide into it exactly are 1, 2, 3, and 6, and the sum of
1, 2, and 3 is itself 6.
Write a recursive method perfectRec to calculate the sum of divisors of n and use it to output whether
n is perfect or not.

Solution:
import j a v a . u t i l . Scanner ;
public c l a s s P e r f e c t R e c 2 {
public s t a t i c void main ( S t r i n g [ ] a r g s ) {
Scanner s c = new Scanner ( System . i n ) ;
System . out . p r i n t l n ( " P l e a s e ␣ e n t e r ␣ ␣ a ␣number : ␣ " ) ;
int query = s c . n e x t I n t ( ) ;

int sum = sumFactorsTo ( query , query −1) ;

i f ( sum == query ) {
System . out . p r i n t l n ( query + " ␣ i s ␣ p e r f e c t " ) ;
} else {
System . out . p r i n t l n ( query + " ␣ i s n ’ t ␣ p e r f e c t : ␣The␣sum␣ i s ␣ " +

12
sum ) ;
}
}

public s t a t i c int sumFactorsTo ( int num , int max) {


i f (max == 0 ) {
return 0 ;
} else {
int sub = sumFactorsTo (num , max − 1 ) ;
i f (num % max == 0 ) {
sub += max ;
}
return sub ;
}
}

/∗ Another s o l u t i o n

p u b l i c s t a t i c i n t sumFactorsTo ( i n t num , i n t i n d e x ) {
i f ( i n d e x == num) {
return 0;
} else {
i n t sumAfter = sumFactorsTo (num , i n d e x +1) ;
i f ( ! ( num % i n d e x == 0) ) {
r e t u r n sumAfter ;
}
r e t u r n i n d e x+ sumAfter ;
}
}

∗/

Exercise 10-22 Look And Say


The look-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, ...
To generate a member of the sequence from the previous member, read off the digits of the previous
member, counting the number of digits in groups of the same digit. For example:

• 1 is read off as “one one” or 11.


• 11 is read off as “two ones” or 21.
• 21 is read off as “one two, then one one” or 1211.

• 1211 is read off as “one one, then one two, then two ones or 111221.
• 111221 is read off as “three ones, then two twos, then one one” or 312211.

Write a recursive Java method lookAndSay and prints the first nth terms of this sequence. Hint: you
can create a helper method that takes a String as a parameter acting as the ith term of the sequence and
returns a String representing the ith +1 term..

Solution:

13
import j a v a . u t i l . Scanner ;
public c l a s s LookAndSay {
public s t a t i c void main ( S t r i n g [ ] a r g s ) {
Scanner s c = new Scanner ( System . i n ) ;
System . out . p r i n t l n ( " P l e a s e ␣ e n t e r ␣ a ␣number : " ) ;
int query = s c . n e x t I n t ( ) ;
lookAndSay ( query , query , " " ) ;
}

public s t a t i c void lookAndSay ( int n , int m, S t r i n g c u r r e n t ) {


i f (m==0)
System . out . p r i n t ( " . . . " ) ;
else {
i f (m==n )
current = "1" ;
else
{
i f (m<n )
current = helper ( current ) ;
}

System . out . p r i n t ( c u r r e n t+" , ␣ " ) ;


lookAndSay ( n ,m−1, c u r r e n t ) ;
}

public s t a t i c S t r i n g h e l p e r ( S t r i n g x )
{
i f ( x . l e n g t h ( ) ==0)
return " " ;

char c = x . charAt ( 0 ) ;
int i ;
int c o u n t e r =1;
f o r ( i =1; i <x . l e n g t h ( ) ; i ++)
{
i f ( c==x . charAt ( i ) )

c o u n t e r ++;
else
break ;
}
return " " + c o u n t e r+ c+ h e l p e r ( x . s u b s t r i n g ( i , x . l e n g t h ( ) ) ) ;

Exercise 10-23 Recursion Tracing 3


Given the following method:
p u b l i c s t a t i c v o i d mystery ( i n t n ) {
i f ( n/2 == 0 ) {

14
System . out . p r i n t ( n ) ;
} e l s e i f ( n % 2 == 0 ) {
System . out . p r i n t ( " ( " + n + " + " ) ;
mystery ( n − 1 ) ;
System . out . p r i n t ( " ) " ) ;
} else {
System . out . p r i n t ( " ( " ) ;
mystery ( n − 1 ) ;
System . out . p r i n t ( " + " + n + " ) " ) ;
}
}

a) What does the method display for the following call:

mystery(6);

Trace your method using a stack.

Solution:
mystery(6); -> (6 + ((4 + ((2 + 1) + 3)) + 5))
b) What does the method displays for any integer?

Solution:
The recursive method mystery that accepts an int n as a parameter and prints out the numbers 1
through n inclusive in a particular pattern that looks like a set of mathematical additions wrapped
in parentheses. The order of the numbers should begin with all of the evens in downward order,
followed by all of the odds upward from 1. Each time a number is added to the pattern, a new set
of parentheses and a + sign are added too.

Exercise 10-24 MergeRec


To be discussed in Tutorials
Write a recursive method mergeRec that given two strings displays the characters of the given strings in
an alternating way. Note that the two strings could be of different length. Note that you are not allowed
to use any additional strings.

Once you execute the following main method

public static void main(String[] args) {


String a = "hlo";
String b = "el";
mergeRec(a,b);
}

the following should be displayed:


hello

public static void mergeRec(String a, String b) {

Solution:

15
public static void mergeRec(String a, String b)
{
helper(a,b,0,0);
}
public static void helper (String a, String b, int i, int j)
{
if(a.length()==i && b.length()==j)
{
return;
}
if(b.length()==j)
{
System.out.print(a.charAt(i)+" ");
helper (a,b,++i,j);
}
else{
if(a.length()==i)
{
System.out.print(b.charAt(j) + " ");
helper (a,b,i,++j);
}
else
{
System.out.print(a.charAt(i) + " " + b.charAt(j) +" ");
helper(a,b,++i,++j);
}
}
}

Exercise 10-25 MergeRec- Final Exam 2015


Write a recursive method mergeRec that given two array of integers displays the elements of the given
arrays in an alternating way. Note that the two arrays could be of different length.
Note that you are not allowed to use any additional arrays. Once you execute the following main
method

public static void main(String[] args) {


int[] a = {1,8,3,4};
int[] b = {5,2};
mergeRec(a,b);
}

the following should be displayed:

1 5 8 2 3 4

Solution:

public static void mergeRec(int[]a, int[]b)


{
helper(a,b,0,0);
}
public static void helper (int[]a, int[]b, int i, int j)

16
{
if(a.length==i && b.length==j)
{
return;
}
if(b.length==j)
{
System.out.print(a[i]+" ");
helper (a,b,++i,j);
}
else{
if(a.length==i)
{
System.out.print(b[j] + " ");
helper (a,b,i,++j);
}
else
{
System.out.print(a[i] + " " + b[j] +" ");
helper(a,b,++i,++j);
}
}
}

17

You might also like