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: Declare a Scanner object to read user input Scanner scanner = new Scanner(System.in); // Step 2: Prompt the user to enter the number of rows System.out.print("Enter the number of rows for the pyramid: "); int numRows = scanner.nextInt(); // Step 3: Outer loop for the number of rows for (int i = 0; i < numRows; i++) { // Step 4: Inner loop for printing leading spaces // The number of spaces decreases with each row for (int j = 0; j < numRows - i - 1; j++) { System.out.print(" "); } // Step 5: Inner loop for printing stars // The number of stars increases with each row (2*i + 1 stars) for (int k = 0; k <= i; k++) { System.out.print("* "); // Print star followed by a space for alignment } // Step 6: Move to the next line after printing stars for the current row System.out.println(); } // Step 7: Close the scanner to prevent resource leaks scanner.close(); } }
Output
Clear
ADVERTISEMENTS