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.
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:
You can download the code:download