i want to generate a pyramid stacks for a given number “n” (“n” – is also a height of the last pyramid). The algorithm should stack (n-1) pyramids. The result should be like this:
height of base pyramid: 4
2
2 4 2
2
2 4 2
2 4 8 4 2
2
2 4 2
2 4 8 4 2
2 4 8 16 8 4 2
I’ve already a code piece to generate last pyramid:
for (i = 1; i <= n; i++) {
for (j = 1; j <= n - i; j++)
System.out.printf("%5s", "");
for (k = 1; k < i; k++)
System.out.printf("%5d", (int) Math.pow(2, k));
for (k = i; k >= 1; k--)
System.out.printf("%5d", (int) Math.pow(2, k));
System.out.println();
}
any idea would be helpful.
Add one more
forloop in the outer most: –So, your loop structure becomes: –
zstarts withn - 2because, the first pyramid is of length 2. And note that in the 2nd inner loop, your condition is changed toi <= n - z.Now, your original set of loops runs
3 times(n - 2) == 2forn = 4, and loop runs till fromz = 2toz = 0. And it creates a pyramid of height(n - z): –(4 - 2) = 2,(4 - 1) = 3,(4 - 0) = 4back to back.