Print Star console using Loop

class Stars {
  public static void main(String[] args) {
    int row, numberOfStars;

    for (row = 1; row <= 10; row++) {
      for (numberOfStars = 1; numberOfStars <= row; numberOfStars++) {
        System.out.print("*");
      }
      System.out.println(); // Go to next line
    }
  }
}

Step-by-Step Explanation:

1. Class Declaration:

class Stars {

A class named Stars is declared. This class contains the logic to print the star pattern.

2. Main Method Declaration:

public static void main(String[] args) {

The main method is the entry point of the program, where the execution starts.

3. Variable Declarations:

int row, numberOfStars;

  • Declared Two integer variables as row and numberOfStars.
  • row will hold a number for a specific row.
  • numberOfStars: This variable determines how many stars to print at the current position.

4. Loop Control for Rows:

for (row = 1; row <= 10; row++) {

  • This is the outer loop that controls the number of rows (from 1 to 10).
  • For each row, we print a certain number of stars based on the row number.

5. Inner Loop for Printing Stars in Each Row:

for (numberOfStars = 1; numberOfStars <= row; numberOfStars++) {

      System.out.print(“*”);

  }

  • The inner loop prints stars in the current row.
  • The number of stars printed in each row is equal to the value of the row.
  • For the first row, row = 1, so 1 star is printed.
  • For the second row, row = 2, so 2 stars are printed.
  • This continues up to the 10th row, where it prints 10 stars.

6. New Line After Each Row:

System.out.println();

At the end of the inner loop (all the stars for the current row have been printed), the System.out.println() is executed. That takes the cursor to the new line so the stars for the next row are printed on a new line.

7. Loops End And Method:

The outer loop continues until row equals 10. After the 10th row, the program terminates.

What Happens During Execution?

  • The outer loop runs 10 iterations (from row = 1 to row = 10) .
  • For each iteration in the outer loop, the inner loop runs row iterations, printing row stars in that row.

Example Output:

Output:

*

**

***

****

*****

******

*******

********

*********

**********

Explanation of the Output:

  • In the first row (row = 1), a single star(*) is printed.
  • In the second row (row = 2), two stars(**) are printed.
  • In the third row (row = 3), three stars(“***”) are printed.
  • Continuing this way till the 10th row where 10 stars(“**********”) are printed.

Conclusion:

It’s a program which shows the nested ‘for’ loops printing out a pattern, where the outer loop prints rows and the inner loop handles printing stars for a row. Finally, this generates a right triangle of stars that increases the stars with every new row.

Leave a Comment

Your email address will not be published. Required fields are marked *