How to print n*n integers with asterisks pattern using Java

In this tutorial, we will learn how to print the n*n integers with asterisks pattern in java.

The program requires an integer as input.

The integer decides the total number of rows and columns to be printed.

Pattern to be printed:

**1
*23
456

ALGORITHM : n*n integers with asterisks pattern

  1. Get the input integer.
  2. The first for loop is initialized with the variable name ‘i’ which maintains the rows of the pattern.
  3. The second for loop is initialized with the variable ‘j’ which prints the ” * ” pattern.
  4. The variable k is initialized to 1 to print the digits pattern.
  5. The third for loop is initialized with the variable ‘j’ and it prints the digits pattern for the desired rows and columns.
  6. The k value is incremented every time to get the next digits.

How to input the number of rows?

int rows;
Scanner input=new Scanner(System.in);
rows=input.nextInt();

In the above code,

The variable name ‘rows’ is initialized.

The System.in used in the Scanner statement is used to get the inputs.

The nextInt() is used to get the integer values only.

INPUT 1:

Enter the number of rows:
3

Also learn:

Java code to print n*n integers with asterisks pattern :

import java.util.*;
public class Main
{
  public static void main(String[] args) {
      int rows,k=1;
      System.out.println("Enter the number of rows:");
      Scanner input=new Scanner(System.in);
      rows=input.nextInt();
  System.out.println("The "+rows+"*"+rows+" integers with asterisks pattern :");
         for(int i=0;i<rows;i++){
             //Code for left side * pattern//
             for(int j=rows-1;j>i;j--){
                System.out.print("*");
             }
             //Code for right side digits pattern//
             for(int j=0;j<=i;j++){
                System.out.print(k++);
             }
            System.out.println("");
         }
    }
}

In the above code,

The number of rows is obtained as input and it is stored under the variable name ‘rows’.

The first for loop maintains the rows. The nested for loops maintains columns.

The second for loop is initialized with the variable name ‘j’. This for loop prints the reverse inverted * pattern.

The third for loop is initialized with the variable name ‘j’. This for loop prints the mirrored right triangle with digits pattern.

The variable ‘k’ is initialized with 1 and each time the value is printed and incremented.

Thus the program prints the desired pattern as output.

OUTPUT 1:

The 3*3 integers with asterisks pattern:
**1
*23
456

INPUT 2:

Enter the number of rows:
4

OUTPUT 2:

The 4*4 integers with asterisks pattern:
***1
**23
*456
78910

Thus the program prints the n*n integers with asterisks pattern as output.

We hope this tutorial helped you to understand how to print the n*n integers with asterisks pattern.

Leave a Reply

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