Recursion Practice:
1)
System.out.println(nertz(5));
public int nertz(int n)
{
if (n == 1)
return 1;
else
return n * nertz(n-1);
}
2)
System.out.println(nrd(0));
public int nrd(int n)
{
if (n > 6)
return n - 3;
else
return n + nrd(n +1);
}
3)
System.out.println(festus(0));
public int festus(int n)
{
if (n > 6)
return n - 3;
else
{
n = n * 2;
return n + festus(n + 1);
}
}
4)
What is displayed by homer(9); ?
public void homer(int n)
{
if (n <= 1)
System.out.print(n);
else
{
homer(n / 2);
System.out.print(“,” + n);
}
}
5)
What is displayed by method1(7); ?
public void method1(int n)
{
if (n <= 1)
System.out.print(n);
else
{
method1(n-2);
System.out.print(“,” + n);
}
}
6)
What is returned by pls(4); ?
public int pls(int n)
{
if (n = = 0)
{
return 5;
}
else if (n = = 1)
{
return 11;
}
else
{
return pls(n - 1) + 2 * pls(n - 2);
}
}
You Try:
1) public int recur(int a)
{
if (a < 3)
return a + 2;
else return 3*recur(a-2);
}
What is returned by a call to recur(7)?
2) public int recur2(int a)
{
if (a < 0) return 0;
else return 3 + recur2(a-3);
}
What is returned by a call to recur2(7)?
3) public int mystery(int b, int p)
{
if (p==1) return b;
else return b*mystery(b, p-1);
}
a) What is returned by a call to mystery(5,3)?
b) What is an appropriate name for mystery?
4) public static int mystery2(int number)
{
if (number/10==0) return 1;
else return 1 + mystery2(number/10);
}
a) What is returned by a call to mystery2(5438)?
b) What is an appropriate name for mystery2?
5) Using the structure of mystery2, create a method called sumDigits that returns the sum of all digits of the number passed.
6) public static int another(int x)
{
if (x >= 3) return x -2;
else return another(x+1) + 2*another(x+2);
}
a) what is returned by a call to another(0)?
b) How many times is the method another called by a call to another(0)?
7) public void printMystery(int x)
{
if (x == 5) System.out.println(x);
else printMystery(x-1);
System.out.println(x+2);
}
What is printed by a call to printMystery(8)?
8) public void printMystery2(int x)
{
if (x == 5) System.out.println(x);
else
{
System.out.println(x+2);
printMystery2(x-1);
}
}
What is printed by a call to printMystery2(8)?