Multiple Choices
-
What is the simplest definition of recursion?
- A method is recursive if it does not take arguments.
- A property is recursive if it has a backing field.
- A method is recursive if it calls itself.
- A method is recursive if it calls a constructor.
- A class is recursive if it inherits from another class.
-
Consider the following code:
What will it display?
- Nothing
- n
- 3 2 1
- 3 2 1 0
- 3 2 1 0 -1 -2 -3 -4 -5 … until the program crashes.
- 2 1 0 -1 -2 -3 -4 -5 … until the program crashes.
- 1 2 3
- 0 1 2 3
-
Consider the following code:
What will it display?
- Nothing
- n
- 3 2 1
- 3 2 1 0
- 3 2 1 0 -1 -2 -3 -4 -5 … until the program crashes.
- 2 1 0 -1 -2 -3 -4 -5 … until the program crashes.
- 1 2 3
- 0 1 2 3
-
Consider the following code:
What will it display?
- Nothing
- n
- 3 2 1
- 3 2 1 0
- 3 2 1 0 -1 -2 -3 -4 -5 … until the program crashes.
- 2 1 0 -1 -2 -3 -4 -5 … until the program crashes.
- 1 2 3
- 0 1 2 3
Exercises
-
What would the following code display?
Solution
10
-
What would the following code display?
Solution
3 -2 2 -1 1 Done
-
What would the following code display?
-
Write a recursive method that takes an
int
as argument, generates a randomint
between0
and this argument, displays it and calls itself with that number. The method should stop when theint
generated is 0.Solution
-
Write a recursive method that takes a
string
as argument and returnstrue
if it is a palindrome. Your method should returntrue
on input"civic"
,"noon"
,"radar"
and""
(empty string), andfalse
on input"test"
and"not a palindrome"
.Hint
Use
Length - 1
to access the last index of the string, and theSubstring
method to create a string without the first and last characters.Solution
-
Write a recursive method that takes an
int
as argument and returns the number of even digits in it. For example, on input631
, the method should return1
since only6
is even.Hint
The
% 10
operation gives the last digit of a number (631 % 10
gives1
), and the/ 10
operation (on integers) removes the last digit from an int (631 / 10
gives63
).Solution