简体   繁体   中英

Number pattern using recursion

I am having a bit of trouble with recursion, my first input will be the starting number and it will keep being subtracted by the second input. Ex) 12 and 3 as inputs and the output is 12 9 6 3 0 3 6 9 12. The printNumPattern method is the recursion method.

private static void printNumPattern(int num1, int num2) {
        int temp = num1;

        System.out.println(num1);

        if(num1 <= 0) {
            
            if(num1 == temp) {
                System.out.println();
            }else {
                printNumPattern(num1+num2,num2);
            }
            
        }else {
            printNumPattern(num1-num2,num2);
        }

    }


    public static void main(String[] args) { 
        Scanner scnr = new Scanner(System.in);
        int num1;
        int num2;

        num1 = scnr.nextInt();
        num2 = scnr.nextInt();
        printNumPattern(num1, num2);
    }

For every 'run' of your printNumPattern , all the variables are unique to just that one run. This goes for int temp , and also for int num1, int num2 (your parameters).

So, in line 2 you say int temp = num1; . If num1 is 0 or below, you then do if (num1 == temp) , which will always be true. The else (that goes to printNumPattern(num1+num2,num2); cannot possibly ever execute.

It sounds like you want temp to be the original input. If you want that, keep passing it along in your printNumPattern method as third parameter.

You can do things after the recursive call, reusing n1 without any calculation:

static void p(int n1,int n2){
  System.out.println(n1);
  if(n1<=0)return;
  p(n1-n2,n2);
  System.out.println(n1);
}

(I'm typing on phone, that's why I shortened names a little)

Some programs may give issues with the code. The author was closest.

    int baseVal = num1;
     System.out.print(num1 + " ");
        if(num1 <= 0)
        {
           if (num1 == baseVal)
               return;
         }
           else
         {
           printNumPattern(num1 + num2, num2);
         }
        }
        else
        {
         printNumPattern(num1 - num2, num2);
         System.out.print(num1 + " ");
         }

This works on any program I used. zybooks, VS, and notepad++. If its zybooks, the program wants an output without line breaks so thats why there is no ln or f("\\n")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM