baileyfunny
baileyfunny

Reputation: 11

How to use recursion technique on the following code?

static void nLines(int n) {
  for (int i= 0; i < n; i++) {
    System.out.println(i);
  }
}

Upvotes: 0

Views: 68

Answers (3)

sushant
sushant

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

user17201277
user17201277

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

dmsovetov
dmsovetov

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

Related Questions