If the number 5 is given to us, it needs to be printed out on the console like 1, 2, 3, 4, 5. This needs to be done recursively. (Java preferably)
In case anyone is wondering these are not homework questions. I am practicing for my midterm a week from now.
Sorry about not posting my work. I was doing something like the below: but getting confused with where to print the rest of the number, and how to stop recursively calling the method with (n – 1). Jacob with his post helped me out. Thanks to everyone who helped.
public void writeNums(int n) {
if (n < 1)
throw new IllegalArgumentException();
if (n == 1) {
System.out.print("1, ");
}
writeNums(n - 1);
We’re not going to write your code for you, but the way recursion works is that you have a function that calls itself, passing in some parameter that changes for each call. It needs to handle the “base case” in which the function does something but doesn’t need to call itself anymore, and also handle the “general case” where the function both does something and calls itself to complete whatever needs to be done. So: