Basic Java Recursion Method

后端 未结 5 1024
别跟我提以往
别跟我提以往 2020-12-07 04:33

I am having a lot of trouble with this basic recursion problem in java; any pointers would be great.

\"Write a static recursive method to print out th

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-07 05:11

    Here's a C# example (I know your doing Java but it's pretty similar)

        public static void Recursive(int counter, int iterations, int value, int multiplier)
        {
            if (counter < iterations)
            {
                Console.WriteLine(value);
                counter++;
                Recursive(counter, iterations, (value * multiplier), multiplier);
            }
        }
    

    So when you run the function you enter the parameters

    • "counter" will always be 0 when you first call it
    • "iterations" is the value of n
    • "value" is your starting value, in your case 2
    • "multiplier" is how much you want to multiply by each iteration, in your case 3

    Every time it runs it will check to see if counter is less than iterations. If it is more, the value is printed, the counter is incremented, the value is multiplied by the multiplier and you add the same parameters back in to the function.

提交回复
热议问题