In: Computer Science
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
JAVA PROGRAM
/**
* class: MyCounter
*
*/
public class MyCounter {
private static final int limit = 1000; // limit
constant is set here
private static int max= limit; //this is the static
instance variable ; set to limit initially
/**
* method recursiveDownAndUp
* It will downCount starting from limit till
param
* and then it will count up from param till
limit
* @param param
*/
private static void recursiveDownAndUp(int
param){
if(param >limit){//base
condition: when param is greater than limit then recursion
stops
return;
}else{
System.out.println(max--);//print max and decrement it
recursiveDownAndUp(param+1); //recursive call with (param+1)
System.out.println(++max);//increment max and print it
}
}
//main method
public static void main(String args[]){
recursiveDownAndUp(953); //count
down from 1000 to 953 and then from 953 to 1000
}
}
===============================
OUTPUT
===============================
1000
999
998
997
996
995
994
993
992
991
990
989
988
987
986
985
984
983
982
981
980
979
978
977
976
975
974
973
972
971
970
969
968
967
966
965
964
963
962
961
960
959
958
957
956
955
954
953
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000