❮ Previous Next ❯

A Java example to print different pyramid.


Pyramid.java

package com.silan;
import java.util.Collections;
public class  Pyramid {
public static void main(String[] args) {
 int rows = 5;
 System.out.println("\n1. Half Pyramid\n");
for (int i = 0; i < rows; i++) {
 for (int j = 0; j <= i; j++) {
System.out.print("*");
}
System.out.println("");
}
 System.out.println("\n2. Full Pyramid\n");
for (int i = 0; i < rows; i++) {
 for (int j = 0; j < rows - i; j++) {
System.out.print(" ");
 }
for (int k = 0; k <= i; k++) {
System.out.print("* ");
}
 System.out.println("");
 //java 8 , one line
  System.out.println("\n3. Full Pyramid (Compact)\n");
for (int i = 0; i < rows; i++) {
System.out.println(String.join("", Collections.nCopies(5 - i - 1, " "))
+ String.join("", Collections.nCopies(2 * i + 1, "*")));
}
 // java 8
 System.out.println("\n4. Inverted Pyramid\n");
 for (int i = rows; i > 0; i--) {
 System.out.println(String.join("", Collections.nCopies(5 - i, " "))
+ String.join("", Collections.nCopies(2 * i - 1, "*")));
}
 }
}

Output


1. Half Pyramid

*
**
***
****
*****

2. Full Pyramid

     *
    * *
   * * *
  * * * *
 * * * * *

3. Full Pyramid (Compact)

    *
   ***
  *****
 *******
*********

4. Inverted Pyramid

*********
 *******
  *****
   ***
    *


❮ Previous Next ❯



  Tutorials

Popular Links

Contact Us

address Plot No-N6/530,2ND Floor
Nayapalli,Jayadev Vihar
      Bhubaneswar-751015
      Email: info@silantechnology.com
      Phone: 0674-2361252
address
39877, sundale dr, apt#101, Fremont, California 94538, USA
       Phone: +1(262)388-7619

facebook twitter google linked in

© 2018 Silan Technology. All Rights Reserved