Pattern printing programs help you to enhance your logical skills, coding, and looping concept. These programs are frequently asked by the interviewer to check the logical skills of the programmer.
In this article, you will learn the simple tricks to develop the logic for Star pattern printing. These tricks will not only help you to understand the Star pattern programs but also help you to understand Alphabet/Character patterns and Number patterns.
Tricks to develop pattern programs logic
Here you are going to learn 8 simple tricks to develop almost all types of pattern programs. All the tricks will be in three steps, first two steps are simple but the third step is a little tricky. The third step is very important for developing the logic.
Let’s see all the 8 tricks one by one:
Trick-1:
Let’s develop the logic for the above pattern:
Let me explain the above steps with simple points:
Step-1: Given pattern
Step-2:
The given pattern can be converted in to the box format like the above.
The box format is repersented in Rows(1,2,3,4,5) and Columns(1,2,3,4,5).
Step-3:
Let’s assume variable n(required number of rows), eg. n=5.
In the above image, the blue color area representing the Line(row) whereas the green color area representing the Star printing.
Line can be represented either in increasing order(1,2,3,4,5) or in decreasing order(5,4,3,2,1).
In the given pattern, first-line is printing 1 star, second-line is printing 2 stars, third-line is printing 3 stars, and so on.
Now you can see in the green area, we have mentioned it like 1 to 1, 1 to 2, 1 to 3, 1 to 4, and 1 to 5.
Now match the common patterns from both(blue area and green area), here you can see we have matched it with red color box.
Now as we have selected lines in increasing order(1,2,3,4,5), so we can write it like 1 to n and then it can be further assumed as the variable i.
Similarly in the green area, we can write it like 1 to i and then it can be further assumed as the vriable j.
Now we can write a for loop for the variable i is like for(int i=1; i<=n; i++){ …} to change the line and another for loop for the variable j is like for(int j=1; j<=i; j++){ …} to print the star. Hence, here we required only two for loops to print the given pattern.
Let’s see the complete logic below:
package com.javacodepoint.patterns;
public class StarPattern {
// Main Method
public static void main(String[] args) {
// Initializing required number of lines/rows
int n = 5;
// Outer loop for the line/row change
for(int i=1; i<=n; i++) {
// Inner loop for the star printing
for(int j=1; j<=i; j++) {
// Printing the star without changing the line
System.out.print("*");
}
// Line/Row change
System.out.println();
}
}
}
Visit the below link to learn all the triks:
https://javacodepoint.com/logical-programs/star-pattern-programs-tricks-in-java/
Top comments (0)