Example Program to Print a Pyramid

I’ve seen quite a few questions about how to write a program to print a pyramid, so I figured I’d write a program to show how it can be done.  Here are two methods to print a pyramid where the width and the character are specified by the user.

Here’s what it looks like when you run the program.

Here's an easy rule. The width must be an odd number that is greater than zero.

How many characters wide do you want the pyramid to be? 11
What character should we use for the pyramid? A
Let's do it with three loops.
     A
    AAA
   AAAAA
  AAAAAAA
 AAAAAAAAA
AAAAAAAAAAA

Let's do it by counting backwards now.
     A
    AAA
   AAAAA
  AAAAAAA
 AAAAAAAAA
AAAAAAAAAAA

Printing the pyramid with three loops:

Both methods start with a for loop to go that counts from 0 to the width by 2.  That will give us 0,2,4, etc., which would seem to mean that it wouldn’t work right.  It does work, because each row gets one more printed character than the row count.  This gives us an odd number of printed characters in each row, starting with 1 and ending with the specified width.

The second loop prints the spaces that help the print character to line up correctly.  Keep in mind that this only works well with fixed width fonts.  The spaceCount variable is updated each time so that it is half of the total width minus the current row.  In the sample output above, I used 11 as the width.  In the first iteration of the row loop, spaceCount will be set to 5, which is (int)(11-0)/5.

The third loop prints the characters that make the pyramid.  It simply counts from 0 to the current value of row.  Note that it uses <= for the compare.  This is what gives us the correct number of printed characters in each row.

for (int row = 0; row < width; row+=2) {
	int spaceCount = (width - row)/2;
	for(int spaces = 0; spaces < spaceCount; spaces++){
		System.out.print(spaceChr);
	}
	for (int chrPosition = 0; chrPosition <= row; chrPosition++) {
		System.out.print(printChr);
	}
	System.out.print("\r\n");
}

Printing the pyramid with two loops:

As with the three loop method, this one starts out by looping from 0 to the width by 2′s.

The second loop is where the magic happens.  It counts backwards from spaceCount+row to 0.  Then, inside the loop, it decides if it should print the space character or the print character.

for (int row = 0; row < width; row+=2) {
  	int spaceCount = (width - row)/2;
  	for (int chrPosition = spaceCount+row; chrPosition >= 0; chrPosition--) {
		if(chrPosition <= row){
			System.out.print(printChr);
		}else{
			System.out.print(spaceChr);
		}
	}
	System.out.print("\r\n");
}

The whole program:

If you want to try the whole thing, here it is.  If you’re looking at this for a school project, remember that you should learn from this and write your own.  Your professor can use google too.

/**
*
* Copyright (c) 2012 Paul Sisco. All Rights Reserved.
*
*/
package com.sisco1.examples;

import java.util.InputMismatchException;
import java.util.Scanner;
/**
*
* @author Paul Sisco
* The PyramidPrinter class will ask the user for the pyramid width and print character,
* and it will print two pyramids using two different methods
*
*/
public class PyramidPrinter {

	/**
	 * Instantiate a new PyramidPrinter object
	 * Get int and string input from the user
	 * -- You could make the main method look for arguments
	 * -- and pass those in to the makePyramid method instead of using the scanner.
	 *
	 * @param args
	 */
	public static void main(String[] args) {
		PyramidPrinter pp = new PyramidPrinter();
		Scanner input = new Scanner(System.in);
		boolean keepAsking = true;
		int width = 0;
		System.out.println("Here's an easy rule. The width must be an odd number that is greater than zero.\r\n");
		while(keepAsking){
			try{
				System.out.print("How many characters wide do you want the pyramid to be? ");
				width = input.nextInt();
				input.nextLine(); // clear out the remaining crlf
				if(width > 2){
					if(width % 2 == 0){
						System.out.println("The value must be an odd integer.");
					}else{
						keepAsking = false;
					}
				}else{
					if(width > 0){
						System.out.println("That's not going to make a very big pyramid. Try 3 or more.");
					}else{
						System.out.println("The value must be a positive integer.");
					}
				}
			}catch(InputMismatchException ime){
				System.out.println("The value must be a positive integer.");
			}
		}

		System.out.print("What character should we use for the pyramid? ");
		String printChr = input.next();

		pp.makePyramid(width, printChr);
	}

	/**
	 * This will print two pyramids using two different methods.
	 * @param width
	 * @param printChr
	 */
	public void makePyramid(int width, String printChr) {
		//make the space character the same length as the printChr
		String spaceChr = "";
		for(int count = 0; count < printChr.length(); count++){
			spaceChr += " ";
		}
		System.out.println("Let's do it with three loops.");
		//this one needs an extra for loop do put the spaces in.
		for (int row = 0; row < width; row+=2) {
			int spaceCount = (width - row)/2;
			for(int spaces = 0; spaces < spaceCount; spaces++){
				System.out.print(spaceChr);
			}
			for (int chrPosition = 0; chrPosition <= row; chrPosition++) {
				System.out.print(printChr);
			}
			System.out.print("\r\n");
		}

		System.out.println("\r\nLet's do it by counting backwards now.");
		//this one doesn't need the extra for loop
		for (int row = 0; row < width; row+=2) {
 			int spaceCount = (width - row)/2;
 			for (int chrPosition = spaceCount+row; chrPosition >= 0; chrPosition--) {
				if(chrPosition <= row){
					System.out.print(printChr);
				}else{
					System.out.print(spaceChr);
				}
			}
			System.out.print("\r\n");
		}
	}
}

Leave a Reply