Reputation: 121
I was wondering how could you write a recursive method that accepts an integer parameter (n) and writes the following sequence: n, n-1, n-2,n-3,..., 0, ... -(n-3), -(n-2), -(n-1), -n. For example: 5,4,3,2,1,0,-1,-2,-3,-4,-5
What would be the base case for this example? How will the method know when to end?
So far I have:
public static void createSequence(int n) {
if (n== 0)
return;
else{
System.out.println(n);
createSequence(n-1);
}
}
This only creates a sequence of positive integers, how can I fix this code?
Upvotes: 0
Views: 2468
Reputation: 1051
The best and easy way to solve your issue is the below code. Here start should be initialized to n before calling this recursive function. (start=n;)
public static void createSequence(int n, int start) {
if (start + n == 0)
return;
else{
System.out.println(n);
createSequence(n-1, start);
}
}
Upvotes: 0
Reputation: 6363
Looks like I'm late to the party, but here's mine:
public static void createSequence(int n){
System.out.println(n);
if(n==0) return;
createSequence(n-Integer.signum(n));
System.out.println(-n);
}
Works with positive and negative input.
Upvotes: 1
Reputation: 716
Fixed !
public static void createSequence(int n) {
if (n== 0){
System.out.println(0);
return;
}else{
System.out.println(n);
createSequence(n-1);
System.out.println(n*-1);
}
}
Upvotes: 0
Reputation: 431
You can pass original number as a second parameter to do a check :
public static void createSequence(int n, int limit) {
if (n < limit)
return;
else{
System.out.println(n);
createSequence(n-1, limit);
}
}
Also by using : createSequence(5, -5);
, it will print:
5
4
3
2
1
0
-1
-2
-3
-4
-5
Upvotes: 0
Reputation: 691705
You just need to write -n after the recursive call:
public static void createSequence(int n) {
if (n == 0) {
System.out.println(n);
return;
}
else {
System.out.println(n);
createSequence(n-1);
System.out.println(-n);
}
}
Upvotes: 2
Reputation: 20618
In such cases, you usually use a helper method for the recursive call:
public static void createSequence(int n) {
createSequenceHelper(n, -n); // be sure that 'n' is positive here
}
private static void createSequenceHelper(int n, int limit) {
if (n >= limit) {
System.out.println(n);
createSequenceHelper(n - 1, limit);
}
}
Upvotes: 0
Reputation: 234795
The easiest, I think, would be to write an auxiliary recursive method:
public static void createSequence(int n) {
writeSequence(n, -n);
}
private static void writeSequence(int current, int limit) {
if (current >= limit) {
System.out.println(current);
writeSequence(current - 1, limit);
}
}
Upvotes: 0