Saturday, October 15, 2016

How to print pyramid pattern of stars and numbers in Java

Hello guys, printing patterns of stars and number is common programming exercise and often asked during coding interviews as well. If you are learning to program or preparing for a coding interviews, knowing how to print a pattern can really help. You can print the Pyramid pattern of stars or numbers using loops and print methods in Java. There are two print methods 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 the 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 like pattern involving multiple stars in one line, a pattern involving stars at different lines, the 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 like operators and looping and branching statements, which will later help to learn data structure and algorithms.


For the sake of example, we'll print the 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 the Java program. The logic for both these patterns is the 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 like # or?

Also, basic knowledge of essential data structure and algorithms is also very important and that's why I suggest all Java programmers join a comprehensive Data Structure and Algorithms course like Data Structures and Algorithms: Deep Dive Using Java on Udemy to improve your knowledge and algorithms skills.




How to print pyramid pattern of stars and numbers in Java

Here is our Java program to print a pyramid of numbers starting from 1 and a 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 stars or numbers but the logic remains the same. It accepts one more parameter to indicate a number of rows in pattern, which means you can use this to print a 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 a 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 the 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 programs. 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 are 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 the sieve of the Eratosthenes algorithm in Java? (solution)
  • How to reverse a singly linked list in Java? (program)
  • How to add two numbers without using the plus operator in Java? (answer)
  • How to remove duplicate characters from String in Java? (program)
  • How to implement a 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 a 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 the 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 Learning
The Coding Interview Bootcamp: Algorithms + Data Structures
Data Structures and Algorithms: Deep Dive Using Java
Algorithms and Data Structures - Part 1 and 2

4 comments :

Unknown said...

Really helpful. Thanks.

Anonymous said...

public void numberPyramidPrinting() {
String result = "";
int count=5;
for (int i = 0; i <= count; i++) {
System.out.println(result = result + i);
}

}

Unknown said...

Help me print this

123454321
1234*4321
123***321
12*****21
1*******1

Unknown said...

Program for
bbbb*
bbb**
bb***
b****
*****

Post a Comment