Java Online Compiler
Example: Star Pyramid Pattern in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Star Pyramid Pattern import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { // Step 1: Initialize Scanner for user input Scanner scanner = new Scanner(System.in); // Step 2: Prompt user for the number of rows System.out.print("Enter the number of rows for the pyramid: "); int numRows = scanner.nextInt(); // Step 3: Outer loop for iterating through each row for (int i = 1; i <= numRows; i++) { // Inner loop 1: Print leading spaces // The number of spaces decreases as the row number increases for (int j = 1; j <= numRows - i; j++) { System.out.print(" "); } // Inner loop 2: Print stars // The number of stars increases by 2 in each subsequent row (1, 3, 5, ...) for (int k = 1; k <= 2 * i - 1; k++) { System.out.print("*"); } // Move to the next line after printing spaces and stars for the current row System.out.println(); } // Step 4: Close the scanner scanner.close(); } }
Output
Clear
ADVERTISEMENTS