Answer to Question #844 in Java | JSP | JSF for Dani
Question #844
Write a java program. User enters size of a triangle from 1-50. Print the triangle in asterisks. The user's input is the middle of the triangle. For example, if the input is 3, the triangle will look like this:
*
**
***
**
*
You have to use nested for loops. So far i did the top half of the triangle:
for(row = 1; row <= size; row++)
{
for(col = 1 ; col <= row ; col++)
{
System.out.print("*");
}
System.out.println();
}
Now i have to do the bottom half and do not know how.
*
**
***
**
*
You have to use nested for loops. So far i did the top half of the triangle:
for(row = 1; row <= size; row++)
{
for(col = 1 ; col <= row ; col++)
{
System.out.print("*");
}
System.out.println();
}
Now i have to do the bottom half and do not know how.
Expert's answer
int size = 50;
for(int row = 1; row <= 2*size - 1; row++)
{
int cnt = row;
if (row > size)
cnt = 2*size - row;
for(int col = 1 ; col <= cnt; ++col)
{
System.out.print("*");
}
System.out.println();
}
for(int row = 1; row <= 2*size - 1; row++)
{
int cnt = row;
if (row > size)
cnt = 2*size - row;
for(int col = 1 ; col <= cnt; ++col)
{
System.out.print("*");
}
System.out.println();
}
Need a fast expert's response?
Submit orderand get a quick answer at the best price
for any assignment or question with DETAILED EXPLANATIONS!
Comments
Leave a comment