pattern 1
Let's dive into the first pattern, the Simple Triangle Star Pattern, and understand how it works.
Pattern:
*
**
***
****
*****
Goal:
We want to print a right-angled triangle made up of stars (*). The triangle should have n rows, where n is the number of lines (in this example, n = 5).
Explanation:
Number of Rows:
The pattern has 5 rows.
The first row has 1 star, the second row has 2 stars, the third row has 3 stars, and so on until the fifth row, which has 5 stars.
Structure:
- Each row number corresponds to the number of stars in that row.
Java Code:
Here's the Java code to generate this pattern:
public class StarPattern {
public static void main(String[] args) {
int rows = 5; // Total number of rows
// Outer loop for the number of rows
for (int i = 1; i <= rows; i++) {
// Inner loop for the number of stars in each row
for (int j = 1; j <= i; j++) {
System.out.print("*"); // Print star
}
System.out.println(); // Move to the next line
}
}
}
Breakdown of the Code:
Variable Initialization:
int rows = 5;
This initializes the variablerowsto 5, which means the pattern will have 5 rows.
Outer Loop (
for (int i = 1; i <= rows; i++)):This loop controls the number of rows.
istarts from 1 and increments by 1 each time, running until it reachesrows.For
i = 1, it prints 1 star. Fori = 2, it prints 2 stars, and so on.
Inner Loop (
for (int j = 1; j <= i; j++)):This loop runs inside the outer loop and controls the number of stars in each row.
The condition
j <= iensures that the number of stars printed is equal to the current row numberi.
Printing Stars (
System.out.print("*");):Inside the inner loop,
System.out.print("*");prints a star without moving to the next line.The stars are printed side by side in the same line.
Move to the Next Line (
System.out.println();):- After printing all the stars in a row,
System.out.println();moves the cursor to the next line, preparing to print the stars for the next row.
- After printing all the stars in a row,
Execution Flow:
1st Iteration:
i = 1→ Inner loop runs once → 1 star is printed → Move to the next line.2nd Iteration:
i = 2→ Inner loop runs twice → 2 stars are printed → Move to the next line.3rd Iteration:
i = 3→ Inner loop runs thrice → 3 stars are printed → Move to the next line.4th Iteration:
i = 4→ Inner loop runs four times → 4 stars are printed → Move to the next line.5th Iteration:
i = 5→ Inner loop runs five times → 5 stars are printed → Move to the next line.
Final Output:
The pattern will look like this when the code is executed:
*
**
***
****
*****
Each line progressively adds one more star, creating a simple and visually appealing right-angled triangle pattern.