Java Program to print pyramid pattern of stars and numbers

You can print Pyramid pattern of stars or numbers using loops and print methods in Java. There are two print method you need to know, System.out.print() and System.out.println(), the difference between print() and println() is that println adds a new line character at the end i.e. it appends \n automatically. which means next time you write something will begin at the new line. On the other hand, if you use print() then the text is appended to the same line. By using these two methods, you can print any kind of pattern in Java program e.g. pattern involving multiple stars in one line, a pattern involving stars at different lines, pyramid of numbers, a pyramid of stars, inverted pyramid pattern of numbers, stars and alphabets, and so on.

Pattern based programs are good for beginner programmers to learn effective use of essential programming constructs e.g. operators and looping and branching statement, which will later help to learn data structure and algorithms.


For the sake of example, we'll print following two patterns in our Java program

1)The Pyramid pattern of stars up to five rows

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

2) Pyramid pattern of numbers up to five rows

1
12
123
1234
12345

These are very simple patterns but the concept and technique you will learn here will help you to print any pattern from Java program. The logic for both these pattern is same, the only difference is the first pattern we are printing stars and on the second pattern, we are printing numbers. If you want you can also print alphabets instead of numbers or any special character e.g. # or ?



How to print pyramid pattern of stars and numbers in Java

Here is our Java program to print pyramid of numbers starting from 1 and pyramid of stars in Java. Since the logic of printing both pyramid of numbers and stars are same, I have just code one method called printPyramidPattern(int rows, boolean isStarPattern). This method takes a boolean to indicate whether we need to print star or numbers but logic remains same. It accepts one more parameter to indicate a number of rows in pattern, which means you can use this to print pyramid pattern of number for 5 rows or 6 rows, it's up to you.


The logic to print this pattern is totally based upon loop and clever use of System.out.print() and System.out.println() method. Suppose, you have to print a pyramid of stars for 5 rows. Since we are printing pyramid, we'll print one star in the first row, two stars in second rows, and 5 stars in the 5th row. In order to achieve that you need to use two for loop, first, will print stars in the same row and use System.out.print() method and the second will be responsible for printing row itself e.g. it will move to next row if the current row is printed. This loop will use System.out.println() method to switch to a new row.  That's it, your pyramid pattern is now read.

Btw, if you are just starting with programming and not very familiar with loops, branching statement etc, I would suggest reading Head First Programming, even though examples are given in Python language, it's a great book to start with programming.

On the other hand, if you are practicing programming problems to improve your coding skills, I also suggest you take a look at problems given in Cracking the Coding Interview, it has more than 189 problems from different tech companies, which are great for practicing and improving coding skills.

Java Program to print pyramid pattern of stars and numbers


Java program to print pyramid pattern of stars
import java.util.Scanner;

/*
 * Java Program print pyramid patterns of stars 
 * and numbers. 
 */

public class Pattern {

  public static void main(String[] args) {

    System.out
        .println("Welcome to Java program to print pyramid patterns of stars and numbers");
    Scanner scnr = new Scanner(System.in);

    System.out.println("Please enter number of rows for pyramid pattern");
    int rows = scnr.nextInt();

    System.out.println("Printing Pyramid pattern of stars");
    printPyramidPattern(rows, true);

    System.out.println("Printing Pyramid pattern of numbers");
    printPyramidPattern(rows, false);

    scnr.close();

  }

  /**
   * Java method to print pyramid pattern of stars for given number of rows. Key
   * here is to remember that you need to use two loops and first loop should
   * start with 1 instead of 0. If you start the first loop also with zero than
   * the first line will be empty as nothing will be printed there. The first
   * loop is responsible for printing number of rows and second, the inner loop
   * is there to print the corresponding number of stars in each row.
   * 
   * @param rows
   */
  public static void printPyramidPattern(int rows, boolean isStarPattern) {

    // outer loop to print number of rows
    for (int i = 1; i <= rows; i++) {

      // inner loop to print stars in individual rows
      for (int j = 1; j <= i; j++) {

        if (isStarPattern) {
          System.out.print("*");
        } else {
          System.out.print(j);
        }
      }
      System.out.println();
    }
  }

}

Output
Welcome to Java program to print pyramid patterns of stars and numbers
Please enter number of rows for pyramid pattern
5
Printing Pyramid pattern of stars
*
**
***
****
*****
Printing Pyramid pattern of numbers
1
12
123
1234
12345


That's all about how to print pyramid patterns of stars and numbers in Java program. You can use the concept of nested loops and print() and println() method to print any kind of patterns in Java. I personally believe you should try with as many patterns as possible because it will improve your coding and programming logic significantly. If you interested you can also solve additional challenges given in Exercises for Programmers: 57 Challenges to Develop Your Coding Skills book or take a look at some of the coding problems from programming job interviews, both are immensely helpful.

How to print pyramid pattern of stars and numbers


Other Coding problems and interview questions you may want to practice
  • How to find the square root of a given number in Java? (solution)
  • How to check if two rectangles intersect with each other in Java? (solution)
  • How to reverse an ArrayList in place in Java? (solution)
  • How to implement sieve of Eratosthenes algorithm in Java? (solution)
  • How to reverse a singly linked list in Java? (program)
  • How to add two numbers without using plus operator in Java? (answer)
  • How to remove duplicate characters from String in Java? (program)
  • How to implement binary search tree in Java? (solution)
  • How to implement pre-order traversal of a binary tree in Java? (solution)
  • How to implement post-order traversal in Java? (program)
  • How to implement in-order traversal in Java? (solution)
  • How to implement binary search algorithm in Java? (solution)
  • How to print all leaf nodes of a binary tree in Java? (solution)
  • How to swap two numbers without using the third variable? (answer)
  • How to implement insertion sort algorithm in Java? (answer)
  • Write a program to implement bubble sort in Java? (solution)
  • How to implement iterative quicksort in Java? (solution)


Further Reading


No comments :

Post a Comment