Triangle of star
In Java language you can print triangle shape using for loop and
also using while loop, here i will show you in simple way to print triangle.
Example
class StarTriangle
{
public static void main(String[] args)
{
int i,j,k;
for(i=1; i<=5; i++)
{
for(j=4; j>=i; j--)
{
System.out.print(" ");
}
for(k=1; k<=(2*i-1); k++)
{
System.out.print("*");
}
System.out.println("");
}
}
}
Output
*
*
*
*
* *
*
* * *
*
* * * *
Syntax to compile and run
java program
Syntax
for compile
-> c:/>javac StarTriangle.java
for run ->
c:/>java StarTriangle
Explnation of Code
·
System.out.print("....."): are used
for display message on screen or console but cursor not move in new line.
·
System.out.println("....."): are used
for display message on screen or console cursor move in new line.
Example
class Star
{
public static void main(String[] args)
{
int i, j, k;
for(i=5;i>=1;i--)
{
for(j=5;j>i;j--)
{
System.out.print(" ");
}
for(k=1;k<(i*2);k++)
{
System.out.print("*");
}
System.out.println();
}
}
}
Output
* * * * * * *
* *
* * * * * * *
* * * * *
* * *
*
Example
class Star
{
public static void main(String[] args)
{
int i,j;
for(i=1; i<=6; i++)
{
for(j=1; j<i; j++)
{
System.out.print("*");
}
System.out.println();
}
}
}
Output
*
* *
* * *
* * * *
* * * * *
Example
class Star
{
public static void main(String[] args)
{
int i, j;
for(i=5;i>=1;i--)
{
for(j=1;j<=i;j++)
{
System.out.print("*");
}
System.out.println();
}
}
}
Output
* * * * *
* * * *
* * *
* *
*
Example
class Star
{
public static void main(String[] args)
{
int i, j, k;
for(i=5;igt;=1;i--)
{
for(j=1;jlt;i;j++)
{
System.out.print(" ");
}
for(k=5;k>=i;k--)
{
System.out.print("*");
}
System.out.println();
}
}
}
Output
*
* *
* * *
* * * *
* * * * *
Example
class Star
{
public static void main(String[] args)
{
int i, j, k;
for(i=5;i>=1;i--)
{
for(j=5;j>i;j--)
{
System.out.print(" ");
}
for(k=1;k<=i;k++)
{
System.out.print("*");
}
System.out.println();
}
}
}
Output
* * * * *
* * * *
* * *
* *
*
Example
class Star
{
public static void main(String[] args)
{
int i, j, k;
for(i=1;i<=5;i++)
{
for(j=i;j<5;j++)
{
System.out.print(" ");
}
for(k=1;k<(i*2);k++)
{
System.out.print("*");
}
System.out.println();
}
for(i=4;i>=1;i--)
{
for(j=5;j>i;j--)
{
System.out.print(" ");
}
for(k=1;k<(i*2);k++)
{
System.out.print("*");
}
System.out.println();
}
}
}
Output
*
* * *
* * * * *
* * * * * * *
* * * * * * *
* *
* * * * * * *
* * * * *
* * *
*
0 Comments