JAVA program to print numbers in PYRAMID design

We all like the pyramids by the way they are built and the enormous size of those pyramids.Today we shall apply it our programming and print the numbers of our desired range.The output of today’s program may look like this.
download

Let us analyze the output.From the output shown we can decide that we need to use two for loops.One for the moving to the other line and the other for number of spaces to taken from the starting place.To print the numbers we use the while loop such that we need to increase the numbers which are printing in each line.To construct the program we shall ask the user number of lines he desired to have in his pyramid and then those numbers of lines with each line increasing the number of elements in it.

import java.util.Scanner;
class pyramid
{
  public static void main(String arg[])
   {
     int space,k=1,z=1;
     Scanner in = new Scanner(System.in);
     System.out.println("Enter how many lines you need in pyramid:");
     int n = in.nextInt();
     for(int i=n;i>0;i--)
      {
         space=i;
         for(int j=0;j<space;j++)
            System.out.print(" ");
         k=1;
         while(z>=k)
          {
             System.out.print(z+" ");
             k++;
           }
         z++;
         System.out.print("\n"); 
       }
    }
}

The output of the above program is:
pyramid
You can download the code:download

Advertisement

About Anuroop D

Very enthusiastic about technology and likes to share my knowledge through blogging. Has Bachelor's in Information Technology and currently pursuing my PhD in Computer Science.
This entry was posted in Java and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s