Question
LAB 1a Part 3: Recursive Counting By Integers Up and Down [ recursiveCounting.java ] 25 points Write a method called recursiveUpAndDown() that takes one non-negative
LAB 1a Part 3: Recursive Counting By Integers Up and Down [ recursiveCounting.java ] 25 points
Write a method called recursiveUpAndDown() that takes one non-negative integer parameter, recursively starts at zero and prints all the integers from zero to the parameter (that is, prints 0, 1, 2, etc. all the way up to the parameter), then recursively starts at the integer parameter and prints all the integers from the parameter to zero (that is, prints the parameter, the parameter - 1, the parameter - 2, etc. all the way down to 0).
Hint: Here's a recursive method named recursiveDownAndUp() that performs the opposite counting being asked for in recursiveUpAndDown() -- it prints from the integer parameter recursively down to 0, then prints from 0 recursively up to 0. The method happens to be in a class called myCounter which has a main() method that invokes recursiveDownAndUp():
class myCounter {
static void recursiveDownAndUp(int i)
{
if (i < 1) // base case
return;
else
{
System.out.printf("%d ",i);
recursiveDownAndUp(i-1); // recursive call
System.out.printf("%d ",i);
return;
}
}
public static void main(String[] args)
{
int i = 2;
recursiveDownAndUp(test);
}
}
Notice recursiveDownAndUp()'s if statement about the value of i in the base case, and also notice recursiveDownAndUp()'s subtraction in the recursive call -- these are the heart of the logic which cause the counting down to occur first and the counting up to occur second.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started