StackTips

Drawing a pyramid using loops in Java

stacktips avtar

Written by

Editorial,  2 min read,  2.53K views, updated on Sept. 17, 2023

Below example prints star like pyramid structure using loop in java.

 public class Pyramid {
	// void main
	public static void main(String[] args) {
		int depth = 10;
		int s = depth, m;

		for (int i = 1; i < = depth; i++) {
			m = s;
			while (s > 0) {
				System.out.print(" ");
				s--;
			}
			for (int j = 1; j < = i; j++) {
				System.out.print("* ");
			}
			System.out.print("\n");
			s = m - 1;
		}
	}
}

Output

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

Beginner's Guide to Java Collections

This course covers the fundamentals of java collections framework covering different data structures in Java to store, group, and retrieve objects.

>> CHECK OUT THE COURSE
stacktips avtar

Editorial

StackTips provides programming tutorials, how-to guides and code snippets on different programming languages.

Related posts

Let’s be friends!

🙌 Stay connected with us on social media for the latest updates, exclusive content, and more. Follow us now and be part of the conversation!