In this post, we will demonstrate the following Java pyramid examples.
1. Triangle Pyramid Example
2. Reverse Triangle Pyramid Example
3. Pyramid Example
4. Reverse Pyramid Example
1. Triangle Pyramid Example
2. Reverse Triangle Pyramid Example
3. Pyramid Example
4. Reverse Pyramid Example
Java Pyramid Examples
1. Triangle Pyramid Example
package net.javaguides.corejava.arrays.programs;
public class TrianglePyramid {
public static void main(final String[] args) {
trianglePyramid(10);
}
public static void trianglePyramid(final int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
Output:
*
**
***
****
*****
******
*******
********
*********
**********
2. Reverse Triangle Pyramid Example
package net.javaguides.corejava.arrays.programs;
public class ReverserTrianglePyramid {
public static void main(final String[] args) {
reverserTrianglePyramid(10);
}
public static void reverserTrianglePyramid(final int n) {
for (int i = n; i > 0; i--) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.print("\n");
}
}
}
Output:
**********
*********
********
*******
******
*****
****
***
**
*
3. Pyramid Example
package net.javaguides.corejava.arrays.programs;
public class PyramidExample {
public static void main(final String[] args) {
pyramid(10);
}
public static void pyramid(final int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - i; j++) {
System.out.print(" ");
}
for (int k = 0; k <= i; k++) {
System.out.print("* ");
}
System.out.println();
}
}
}
Output:
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
4. Reverse Pyramid Example
package net.javaguides.corejava.arrays.programs;
public class PyramidsExamples {
public static void main(final String[] args) {
reversePyramid(10);
}
public static void reversePyramid(final int n) {
for (int i = n; i >= 0; i--) {
for (int j = 0; j <= n - i; j++) {
System.out.print(" ");
}
for (int k = 0; k <= i; k++) {
System.out.print("* ");
}
System.out.println();
}
}
}
Output:
* * * * * * * * * * *
* * * * * * * * * *
* * * * * * * * *
* * * * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
Comments
Post a Comment