0

I'm quite stuck on this piece of code, the assignment is simple: "given a number n or value, print on the console the sequence from n to 1 and from 1 to n (repeating the number 1 so it should be like this '5432112345').

The recursion per se is not a problem, the real problem is the second part due to the fact that i cannot use any other variable only n. I cannot store the starting value nowhere, since each time i call the method it would be actualized.

Here is the code so far:

public int mirrorRecursive(Integer value){
       if (value < 1){        //in case the given value is less than 1 it won't print anything
            return value;
        }
        if(value == 1){        //in case the value is 1, it will be printed and stop the calling
            System.out.print(value);
        }else{                 //in case the value is not 1 or less, it will print and call again the method
            System.out.print(value);
            mirrorRecursive(--value);
        }

        return value;
}
2
  • You shouldn't really use Stackoverflow to solve classroom assignments. Commented Jan 7, 2020 at 16:11
  • 1
    Actually i think is a good tool to use, either you are a student or a professional programmer. It's not always easy to understand a concept, or maybe you just miss a simple step. Everyone has the right to ask and sound stupid, if the purpose is to learn. Commented Jan 11, 2020 at 16:24

1 Answer 1

5

I'm not sure what's the use of the value returned by the method, but in order to print the desired output, all you need is:

public static int mirrorRecursive(Integer value){
  System.out.print(value);
  if (value > 1) {
    mirrorRecursive(value - 1);
  }
  System.out.print(value);

  return value;
}

i.e. print the current number before and after the recursive call, and make a recursive call as long as value > 1.

Sign up to request clarification or add additional context in comments.

1 Comment

This is the answer, but I don't think that in stackoverflow we should solve homework assignments ;-) And as an improvement the method can be void.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.