Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Number Pyramid - Basic Loop

807589Mar 27 2008 — edited Aug 5 2008
Ive been stuck on this for like 2 weeks, does anyone have some advice? The program is supposed to print out a number pyramid that looks like this:

1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1

and another that looks like

1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1

These next 2 i have already figured out, ill post my code so u can get an idea of what im workin with:
import javax.swing.JOptionPane;

public class Pyramid1 {

public static void main(String[] args) {

int numberOfLines = 6;

for (int row=1; row <= numberOfLines; row++){   //Prints the lines
	for (int column = 6; column <= numberOfLines - row; column++)  //Prints the spaces
	System.out.print("  ");


	for (int num = 1; num <= row; num++)   //Prints the numbers
	System.out.print(" " + num);

	System.out.println();  //Goes to the next line
}
}
}
This prints:
1
12
123
1234
12345
123456

And:
  import javax.swing.JOptionPane;

public class Pyramid3 {

public static void main(String[] args) {

int numberOfLines = 6;

for (int row=1; row <= numberOfLines; row++){  //lines
	
	for (int column = 1; column <= numberOfLines - row; column++)   //spaces
	System.out.print("  ");

	for (int num = row; num >= 1; num--)  //numbers
	System.out.print(" " + num);


	System.out.println();  //next line
}
}
}
And this one looks like:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Sep 2 2008
Added on Mar 27 2008
6 comments
470 views