Reputation: 11
static void nLines(int n) {
for (int i= 0; i < n; i++) {
System.out.println(i);
}
}
Upvotes: 0
Views: 68
Reputation: 1111
You can recurse on n
.
static void nLines(int n) {
if( n <= 0) {
return;
} else {
int x = n - 1;
nLines(x);
System.out.println(x);
}
}
You call the function like so:
nLines(n);
Upvotes: 1
Reputation:
Try this.
static void nLines(int n) {
if (--n < 0) return;
nLines(n);
System.out.println(n);
}
public static void main(String[] args) {
nLines(3);
}
output:
0
1
2
Upvotes: 0
Reputation: 299
Here is a recursive function to print n lines:
static void nLinesRecursive(int n) {
int next = n - 1;
if (next >= 0) {
nLinesRecursive(next);
System.out.println(next);
}
}
Upvotes: 0