In this article, you will learn how to print downward triangle star pattern in Java.
This is how a downward triangle star pattern looks:
number of rows = 6 Output: * * * * * * * * * * * * * * * * * * * * *
Example 1: Program to print downward triangle star pattern
public class JavaExample { public static void main(String[] args) { int numberOfRows = 7; for (int i = numberOfRows - 1; i >= 0; i--) { for (int j = 0; j <= i; j++) { System.out.print("*"); } //New line for new row System.out.println(); } } }
Output:
Example 2: Print downward triangle star pattern based on user input
In this example, program prints the downward triangle star pattern based on the number of rows entered by user. The logic is same as above example, except here the numberOfRows is not hardcorded and its value is captured by using
import java.util.Scanner; public class JavaExample { public static void main(String[] args) { int numberOfRows; System.out.println("Enter number of rows: "); Scanner sc = new Scanner(System.in); numberOfRows = sc.nextInt(); for (int i = numberOfRows-1; i >= 0; i--) { for (int j = 0; j <= i; j++) { System.out.print("*"); } //New line for new row System.out.println(); } } }
Output:
Leave a Reply