Can this iterative method be implemented recursively?
public class Main
{
public static void pyr(int n)
{
for(int i=1;i<=n;i++)
{
for(int j = 1;j<=i;j++)
{
System.out.print("*");
开发者_如何学JAVA }
System.out.println();
}
}
}
Can such a code for a pyramid like shape of asteriks be implemented recursively ? if so especially the 2 loops as the first one is for leveling while the second is used to fill each level.
The answer is yes - basically everything iterative can be done recursively, sometimes it is much easier, but more time consuming.
For your question - this does the trick:
public static void main(String[] args)
{
printPyramid(7);
}
public static void printPyramid(int lines)
{
if (lines > 1)
{
printPyramid(lines-1);
}
printLine(lines);
System.out.println("");
}
public static void printLine(int level)
{
if (level > 0)
{
System.out.print("*");
printLine(level-1);
}
}
"Any function that can be evaluated by a computer can be expressed in terms of recursive functions without the use of iteration, in continuation-passing style; and conversely any recursive function can be expressed in terms of iteration." Source: http://kevin.vanzonneveld.net/techblog/tag/recursion/
Edit: added source link.
Sure, just have a look at the chapter of the wikipedia article. I've seen a mathematic proof also but I forgot where I can find it.
In your case just use two methods. One prints stars as long as the input parameter is greater 0.
public void static printStar(int n) {
if(n > 0) {
System.out.print("*");
--n;
printStar(n);
}
}
This code handles your inner loop.
public void static printPyramid(int n, int start) {
if(start >= n) {
return;
}
printStar(start);
++start;
printPyramid(n, start);
}
This code handles your outer loop. Where start is your i.
精彩评论