Thursday, 26 May 2016

How to print Pyramid Pattern of Numbers in Java

Write a Java Program to print the following Pyramid pattern of numbers:

1
12
123
1234
12345
1234
123
12
1

You can easily print above pattern using two loops and with the help of print() and println() method of PrintStream. You can access them using System.out object as System.out.print() and System.out.println().

But, in this program, I'll show you can print this patter by using just one loop instead of two.




Java Program to Print Pyramid Pattern

/**
 * Java Program to print following pyramid pattern of numbers
 *  1
    12
    123
    1234
    12345
    1234
    123
    12
    1
 *
 * @author http://simplejava8.blogspot.com/
 *
 */
public class Pattern {
    public static void main(String[] args) {
       
        // print pyramid pattern
        printPattern();
    }
   
   
    public static void printPattern(){
        int x = 0, y = 2;
        while (y > 0) {
            if (x == 0) {
                // printing pattern
                for (int i = 1; i <= 5; i++) {
                    for (int j = 1; j <= i; j++) {
                        System.out.print(j);
                    }
                   
                    System.out.println();
                }
                x++;
            } else {
                for (int i = 1, r = 5 - 1; i <= 5 - 1; i++, r--) {
                    for (int j = 1; j <= r; j++) {
                        System.out.print(j);
                    }
                    System.out.println();
                }
            }
            y--;
        }
    }
}

Output
1
12
123
1234
12345
1234
123
12
1


Happy Coding Java Programmer. If you have any problem understanding code, please ask me.

3 comments:

  1. Hey, This blog is really helpful. Thank you for such kind of post.
    You can go and find some more similar post over here :Programming Boss
    Thanks again!!

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Hey, this is a great article. You can find more examples here: https://www.programmingboss.com/2015/03/how-to-print-stars-pattern-in-java.html

    ReplyDelete