Given a number N, the task is to print the following pattern:-
Examples:
Input : 10
Output :
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
Input :5
Output :
*
* *
* * *
* * * *
* * * * *
There is a nested loop required to print the above pattern. The outer loop is used to run for the number of rows given as input. The first loop within the outer loop is used to print the spaces before each star. As you can see the number of spaces decreases with each row while we move towards the base of the triangle, so this loop runs one time less with each iteration. The second loop within the outer loop is used to print the stars. As you can see the number of stars increases in each row as we move towards the base of the triangle, so this loop runs one time more with each iteration. Clarity can be achieved if this program is dry run.
// Java Program to print the given pattern import java.util.*; // package to use Scanner class class pattern { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the number of rows to be printed"); int rows = sc.nextInt(); // loop to iterate for the given number of rows for (int i = 1; i <= rows; i++) { // loop to print the number of spaces before the star for (int j = rows; j >= i; j--) { System.out.print(" "); } // loop to print the number of stars in each row for (int j = 1; j <= i; j++) { System.out.print("* "); } // for new line after printing each row System.out.println(); } } } |
Recommended Posts:
- Inner reducing pattern printing
- Printing Heart Pattern in C
- Printing string in plus ‘+’ pattern in the matrix
- Program for Expressionless Face Pattern printing
- Pattern Printing question asked in CGI Coding Round
- Program to print hollow Triangle pattern
- Print symmetric double triangle pattern
- Program for incrementing/decrementing triangle pattern
- Printing Integer between Strings in Java
- Programs for printing pyramid patterns in Java
- Java Program for Maximum height when coins are arranged in a triangle
- Sum of upper triangle and lower triangle
- Builder Pattern in java
- Matcher pattern() method in Java with Examples
- Java Program for KMP Algorithm for Pattern Searching
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



