Print equilateral triangle in java
Below prints Equilateral Triangle.
public class PrintEqulateralTriangle {
public static void main(String[] args) {
int numberOfRow = 10;
int numberOfStars = numberOfRow + (numberOfRow - 1);
int median = (numberOfStars+1)/2;
for(int i=1; i<=numberOfRow; i++){
int start = (i==1 ? median : (median - i + 1));
int end = (i==1 ? median : (median + i - 1));
for(int j=1; j<=end;j++){
if((j>= start) && (j <= end)){
System.out.print("* ");
}else{
System.out.print(" ");
}
}
System.out.println();
}
}
}
Output:
--------
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * *
Note: This might not show perfect equilateral triangle in browser due to html rendering. But the when you execute code, it will print perfect equilateral triangle in the console.
public class PrintEqulateralTriangle {
public static void main(String[] args) {
int numberOfRow = 10;
int numberOfStars = numberOfRow + (numberOfRow - 1);
int median = (numberOfStars+1)/2;
for(int i=1; i<=numberOfRow; i++){
int start = (i==1 ? median : (median - i + 1));
int end = (i==1 ? median : (median + i - 1));
for(int j=1; j<=end;j++){
if((j>= start) && (j <= end)){
System.out.print("* ");
}else{
System.out.print(" ");
}
}
System.out.println();
}
}
}
Output:
--------
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * *
Note: This might not show perfect equilateral triangle in browser due to html rendering. But the when you execute code, it will print perfect equilateral triangle in the console.
Comments
Post a Comment