How to Draw Pyramids in Java
One of the first steps to becoming a Java programmer entails learning how to create a "for" loop, wherein a specific set of actions are reiterated until a predefined counter reaches a certain value. The next step is to build nested "for" loops. This involves creating a "for" loop and then placing another "for" loop into the initial loop. One way to learn and practice doing this is by drawing a star pyramid -- or a pyramidal shape composed of the * symbol.
Instructions
-
-
1
Establish the class by using the public function:
public class CLASSNAME
{
}Replace "CLASSNAME" with the name you would like to use for the class.
-
2
Setup the class's inputs and outputs using the public static void main function:
public static void main(String args[])
{
}Place it between the class brackets.
-
-
3
Type the initial "for" loop, which will increment the variable "p" by 1 every time the program finishes drawing a row:
for(int p=1; p<10; p++)
{
}Insert it between the public static void main brackets.
-
4
Create the second "for" loop, which will increment the variable "q" by 1 while in a row and draw another portion of the pyramid:
for(int q = 0; q < p; q++)
{
System.out.print("*");
} -
5
Direct the program to go to the next line every time every time it finishes drawing a row and is ready to draw the next row:
System.out.println();
Insert this after the second "for" loop but before the first "for" loop's second bracket.
-
1
- Photo Credit Ryan McVay/Digital Vision/Getty Images