Write a method called recursiveDownAndUp() that takes one non-negative integer parameter, recursively starts at one thousand and prints all the integers from one thousand to the parameter (that is, prints 1000, 999, etc. all the way down to the parameter), then recursively starts at the integer parameter and prints all the integers from the parameter up to one thousand (that is, prints the parameter, the parameter + 1, the parameter + 2, etc. all the way up to 1000).
Hint: Here's a recursive method named recursiveUpAndDown() that performs the opposite counting being asked for in recursiveDownAndUp() -- it prints from the integer parameter recursively up to 1000, then prints from 1000 recursively down to the integer parameter. The method happens to be in a class called myCounter which has a main() method that invokes recursiveUpAndDown():
class myCounter{
static void recursiveUpAndDown(int i)
{
if (i < 1) // base case
return;
if (i > 1000) // base case
return;
else
{
System.out.println(i);
recursiveUpAndDown(i + 1); // recursive call
System.out.println(i);
return;
}
}
public static void main(String[] args)
{
int i = 1;
recursiveUpAndDown(i);
}
}
Notice recursiveUpAndDown()'s if statements about the value of i in the base case, and also notice recursiveUpAndDown()'s addition in the recursive call -- these are the heart of the logic which cause the counting up to occur first and the counting down to occur second
class myCounter{
static void recursiveDownAndUp(int i){
if(i < 1)
return;
else{
System.out.println(i);
recursiveDownAndUp(i - 1); // recursive call
return;
}
}
static void recursiveUpAndDown(int i)
{
if (i < 1) // base case
return;
if (i > 1000) // base case
return;
else
{
System.out.println(i);
recursiveUpAndDown(i + 1); // recursive call
return;
}
}
public static void main(String[] args)
{
int i = 1, j = 1000;
System.out.println("RecursiveDownAndUp");
recursiveDownAndUp(j);
System.out.println("RecursiveUpAndDown");
recursiveUpAndDown(i);
}
}
/* PLEASE UPVOTE */
Get Answers For Free
Most questions answered within 1 hours.