Reputation: 35
I need to print out a triangle that looks like this:
*
**
***
****
The code I have right now
for(line = 0; line < size; line++){
for(count = 0; count < line; count++){
System.out.print("*");
for(space = 0; space < line; space++)
System.out.print(" ");
}
System.out.println();
}
I get this
*
**
***
****
*****
******
Upvotes: 0
Views: 4034
Reputation: 219
class Pyramid
{
public static void main(String args[])
{
java.util.Scanner pyr=new java.util.Scanner(System.in);
System.out.println("type a no. to make Pyramid");
int n= pyr.nextInt();
for (int i=1; i<=n; i++)
{
for(int j=n; j>i; j--)
{
System.out.print(" ");
}
for(int k=1; k<=i; k++)
{
System.out.print("* ");
}
System.out.println();
}
}
Upvotes: 0
Reputation: 3197
You need to first print the prefix spaces. and then print the stars.
Have a try with this:
int line = 0;
int size = 6;
int count = 0;
int space = 0;
for (line = 0; line < size; line++) {
//print spaces
for (space = 0; space < line; space++)
System.out.print(" ");
//Print stars
//Note: here count condition should be count < line+1, rather than count < line
//If you do not do so, the first star with print as space only.
for (count = 0; count < line+1; count++) {
System.out.print("*");
}
System.out.println();
}
Output in console:
*
**
***
****
*****
******
Upvotes: 0
Reputation: 326
for(line = 0; line < size; line++){
for(space = 0; space < line; ++space)
System.out.print(" ");
for(count = 0; count < line; count++)
System.out.print("*");
System.out.println();
}
Upvotes: 2
Reputation: 708
You're printing the spaces on the same line. Call System.out.println();
before printing the spaces.
Edit - Example:
for (line = 0; line < size; line++){
for(space = 0; space < line - 1; space++)
System.out.print(" ");
for (count = 0; count < line; count++)
System.out.print("*");
System.out.println();
}
Upvotes: 0