In this tutorial, you will learn how to write java program to print right down mirror star pattern.
This is how a right down mirror star pattern looks:
number of rows = 5
output:
* * * * *
* * * *
* * *
* *
*
Example 1: Program to print Right Down Mirror Star Pattern
public class JavaExample { public static void main(String args[]) { //Initialized number of rows in the pattern int numberOfRows=8; //This outer loop will run 8 times as number of rows is 8 for (int i=numberOfRows; i>=1; i--) { //This inner for loop will print spaces in each row for (int j=numberOfRows; j>i;j--) { System.out.print(" "); } //This inner for loop will print stars in each row for (int k=1;k<=i;k++) { System.out.print("*"); } //To move the cursor to new line for next row System.out.println(); } } }
Output:
Example 2: Print Right Down Mirror Star Pattern based on user input
This program is same as above program except that here the number of rows is entered by user. The program asks the user to enter the number of rows and based on the input it prints the pattern consisting of entered rows.
import java.util.Scanner; public class JavaExample { public static void main(String args[]) { //This represents the number of rows in the pattern int numberOfRows; System.out.println("Enter the number of rows: "); //Getting the number of rows input from user Scanner sc = new Scanner(System.in); numberOfRows = sc.nextInt(); sc.close(); //This outer loop will run based on the number entered by user //If user enters 5 as number of rows, this will run 5 times //If user enters 10, it will run 10 times. for (int i=numberOfRows; i>=1; i--) { //Inner loop: Print spaces for each row for (int j=numberOfRows; j>i;j--) { System.out.print(" "); } //Inner loop: Print Stars for each row for (int k=1;k<=i;k++) { System.out.print("*"); } //To move the cursor to new line for next row System.out.println(); } } }
Output:
Leave a Reply