【问题标题】:How To Convert a nested for Loop to Recursive如何将嵌套的 for 循环转换为递归
【发布时间】:2019-04-14 17:48:42
【问题描述】:

谁能帮我把这个 for 循环转换成递归方法: 到目前为止,我添加了这两种方法,但我仍然想更改第二个循环。 提前谢谢你。

       public void makeDesign1() {
    int x;
    for (int i = 0; i < 5; i++) // For loop is the one creating the rows
    {
        for (x = 4; x > i; x--) // Nested loop is the one creating the columns 
        {
            System.out.print("*");
        }
        System.out.println();
    }
    System.out.println();

}

public static int makeDesign1Recur(int i) {

    if (i == 0) {
        return 0;
    }
    System.out.print("*");
    return (makeDesign1Recur(i-1));
}
// How to convert this second loop recursive?
public static void makeDesignRow(int i){
   for ( int x = i; x>=0; x--){
       makeDesign1Recur(x);
       System.out.println("");
   }


}

【问题讨论】:

  • 我认为,您的内部 for 循环甚至不会执行,因为 i 的最大值为 4。您可能希望在您的问题中添加问题陈述。顺便说一句,使用两个for 循环来表达问题并没有错。
  • 请展示您的尝试并突出显示您遇到问题的地方。我们不会为您完成工作,但如果您展示您所做的工作,我们会为您提供帮助。
  • 它确实有效。它打印如下内容:
  • 类似这样,屏幕上开始有几个:**** *** ** *
  • 我需要将相同的for循环转换为递归方法。

标签: java loops for-loop recursion


【解决方案1】:

我认为第一步是正确地重新定义makeDesign1()。我们想为我们的绘图传递一个尺寸。我们还想稍微改变边界,让大小为 1 的时候画一颗星,而不是像原来的那样:

public static void makeDesign(int n) 
{
    for (int i = 0; i < n; i++) // For loop is the one creating the rows
    {
        for (int x = n; x > i; x--) // Nested loop is the one creating the columns 
        {
            System.out.print("*");
        }

        System.out.println();
    }

    System.out.println();
}

下一步是让两个循环都倒计时到 1,以便在时机成熟时简化递归:

public static void makeDesign(int n) 
{
    for (int i = n; i > 0; i--) // For loop is the one creating the rows
    {
        for (int x = i; x > 0; x--) // Nested loop is the one creating the columns 
        {
            System.out.print("*");
        }

        System.out.println();
    }

    System.out.println();
}

现在我们可以简单地将每个循环转换成它自己的递归函数,一个调用另一个:

public static void makeDesign(int n) 
{
    if (n > 0)
    {
        makeDesignRow(n);
        makeDesign(n - 1);
    }
    else
    {
        System.out.println();
    }
}

public static void makeDesignRow(int x)
{
    if (x > 0)
    {
        System.out.print("*");
        makeDesignRow(x - 1);
    }
    else
    {
        System.out.println();
    }
}

输出

传递makeDesign() 10 的参数,我们得到:

> java Main
**********
*********
********
*******
******
*****
****
***
**
*

> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-29
    • 1970-01-01
    • 2013-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多