KING SAUD UNIVERSITY
COLLEGE OF COMPUTER AND INFORMATION SCIENCES
INFORMATION TECHNOLOGY DEPARTMENT
CSC 113: Java Programming 2 Tutorial 7 Recursion
Q1) Consider the following UML
class File {
private int id;
public File(int id) {
[Link] = id;
}
public int getid() { return id; }
}
// Parent class: Aggregates File objects
class Folder {
private String folderName;
// Aggregation: Folder has-a list of Files
private File[] files;
private int nOf;
public Folder(String folderName, int size ) {
[Link] = folderName;
files = new File[size];
}
public boolean addFile (File f){
if([Link]==nOf) return false;
else
files[nOf++]=f;
return true;
}
1
KING SAUD UNIVERSITY
COLLEGE OF COMPUTER AND INFORMATION SCIENCES
INFORMATION TECHNOLOGY DEPARTMENT
CSC 113: Java Programming 2 Tutorial 7 Recursion
a) Implement the recursive method copyfiles , this method copy files object from
array flist into current array files starting from index i in flist.
public void copyfiles(File[] flist, int i) {
if ((i == [Link])|| (nOf==[Link]))
return;
files[nOf++] = flist[i];
copyfiles(flist,i++);
}
b) Implement the recursive method replacefile , this method replaces all target files in
the current array files with the replacement file
public void replacefile(File target,File replacement, int i) {
// Base Case: End of array reached
if (i == nOf) {
return;
}
// If match found, replace it
if (files[i] == target) {
files[i] = replacement;
}
// Recursive Step: Move to next element
replacefile(target, replacement, i++);
}
Q2) Consider the following method
public static int test(String s, int last) {
if (last < 0) {
return 0;
}
if ([Link](last) == '0') {
return 2 * test(s, last-1);
}
return 1 + 2 * test(s, last-1); }
what is the result of calling the method using the following values : test("01101", 4) ?
13
2
KING SAUD UNIVERSITY
COLLEGE OF COMPUTER AND INFORMATION SCIENCES
INFORMATION TECHNOLOGY DEPARTMENT
CSC 113: Java Programming 2 Tutorial 7 Recursion
Q3: What is the output of the following program?
public class Test2 {
public static void main(String [] args) {
[Link](recursion(101));
[Link](recursion(99));
[Link](recursion(0));
}
public static int recursion (int n)
{
if (n > 100)
return n - 10;
if (n == 0)
return recursion(n + 101) / (n+1);
[Link]("R method");
return recursion(recursion(n + 11)); }}
Output
91
R method
R method
91
91
Q4) write a recursive method to test if a string is palindrome or not .
public static boolean p(string s, int i, int f)
if (i < f) {
if (s[i] == s[f]) {
return p(s, i+1, f-1); }
else { return false; } }
else { return true; } }