I want to draw a triangle with stars like below using for loop, but i really don\'t have any idea of how to do this ? Triangle is going to be like this:
*
**
**
public static void main(String[] args)
{
StringBuilder stars = new StringBuilder();
for(int i = 0; i <= 10; i++)
{
stars.append("*");
System.out.println(stars);
}
}
Or alternatively using nested loops: (This is what the exercise was really trying to get you to do)
public static void main(String[] args)
{
for(int i = 0; i <= 10; i++)
{
for(int j=0; j<=i; j++)
{
System.out.print("*");
}
System.out.print("\n");
}
}
This can give you solution of your question.
class Seven
{
public static void main(String arg[])
{
for(int i=0;i<=8;i++)
{
for(int j=8;j>=i;j--)
{
System.out.print(" ");
}
for(int k=1;k<=(2*i+1);k++)
{
System.out.print("*");
}
System.out.println("\n");
}
}
}
public class StarA {
public static void main(String[] args) {
for( int i = 1; i <= 5; i++ )
{
for( int j = 0; j < i; j++ )
{
System.out.print("*");
}
System.out.println();
}
}
}
import java.util.Scanner;
public class apple{
public static void main(String[] args){
int c,r;
for(c=1; c<=10; c++){
for(r=1; r<=c; r++){
System.out.print("*");
}
System.out.println();
}
}
for(int aj =5;aj>=1;aj--){
for (int a1 = 0; a1 < aj; a1++) {
System.out.print(" ");
}
for(int a2 = 5;a2>=aj;a2--) {
System.out.print("$");
}
for(int a2 = 5;a2>aj;a2--) {
System.out.print("$");
}
System.out.println();
Just to comment on your internet-found code...
for
loops should always start from 0
, unless you have a specific reason to start from 1
. Its a good habit to practice starting from 0
for everything, as it'll help you when it comes to using java arrays
.for
loops inside each other... The outside loop is just controlling how many lines there are in the triangle (8
in this case). The inner loop is writing the number of stars for that line. This isn't the best way of achieving the result, but it would work correctly.for
loop at the bottom is writing out stars to appear like the trunk of a tree.Hope this helps your understanding.