Home > database >  How to print numbers from 1 to n using recrsion in java
How to print numbers from 1 to n using recrsion in java

Time:12-08

public static void increase(int N){
    int a = 1;

    if(b <= N) {
        System.out.print(a   " ");
        a  ;
    } else {
        increase(N);                
    }
}

I can see the problem with this approach that the int a gets initialized to 1 every time the code goes for a recursive call. Can anyone suggest the correct solution?

CodePudding user response:

You have to create one additional private method to count current value.

public static void increase(int N) {
    increase(1, N);
}

private static void increase(int a, int N) {
    if (a <= N) {
        if (a > 1)
            System.out.print(' ');

        System.out.print(i);
        increase(a   1, N);
    }
}

CodePudding user response:

You can just put a outside the function:

// I don't know your class
private a = 1;

static void increase(int N){
        
    int a = 1;
    if(b <= N){
        System.out.print(a " ");
        a=a 1;
    
        
    }
    else
    {
        increase(N);                
    }

}

CodePudding user response:

static void increase(int N, int a){
    if (a>N) return;
    System.out.print(a " ");
    a=a 1;
    increase(N,a);
}

//example call from static context print 1-100
increase(100,1);

CodePudding user response:

  public static void main(String[] args) {
        increase(10,1);
    }
    private static  void increase(int N,int begin){

        if(begin <= N){
            System.out.print(begin " ");
            begin=begin 1;
            increase(N,begin);
        }
        return;
    }
  • Related