Print Perfect Triangles in Java with Minimal Loops
While relearning Java, the author created a concise solution that uses a single if‑else check to print both a right‑aligned and an equilateral triangle in the console, reducing the usual multiple‑loop approaches and providing complete code examples with output images.
The author, revisiting Java, needed to complete an assignment to print a right‑aligned triangle. After examining many online answers that relied on several nested for‑loops, they devised a simpler approach that uses a single if‑else decision based on the triangle's vertex, thereby minimizing loop usage.
Below is the code for the right‑aligned triangle. The outer loop iterates over the rows, and the inner loop prints spaces until the vertex column is reached, after which asterisks are printed.
for (int i = 0; i < 10; i++) {
for (int k = 0; k < 9 + i; k++) {
if (k < 10 - i) {
System.out.print(" ");
} else {
System.out.print("* ");
}
}
System.out.println("
\t");
}The console output of this program is shown below:
For an equilateral triangle, the author adds a counter variable n to alternate between printing a star and skipping a position, while keeping the same loop structure. This yields a symmetric shape.
for (int i = 0; i < 10; i++) {
int n = 1;
for (int k = 0; k < 9 + i; k++) {
if (k < 10 - i) {
System.out.print(" ");
} else if (n % 2 == 1) {
n++;
System.out.print(" * ");
} else {
n++;
}
}
System.out.println("
\t");
}The resulting output image for the equilateral triangle is:
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
