Square pattern display using java

In this program, we will learn how to display the pattern of the square using Java.
We will use some while loops and for loops for the iteration.

  1. Import the util class
  2. Use the Scanner method for input

How to take input from the user

Scanner scanner=new Scanner(System.in);
     int userInteger;
     
     System.out.println("please enter a number between 1 to 15");
     userInteger=scanner.nextInt();

 




In this program, we have seen a scanner keyword by the help of scanner keyword we take input and we take an integer variable to store the input value.

Java program to print square pattern

 import java.util.*;
 
 public class SquareDispplay{
   public static void main(String s[])
   {
     Scanner scanner=new Scanner(System.in);
     int userInteger;
     
     System.out.println("please enter a number between 1 to 15");
     userInteger=scanner.nextInt();
     
     while(userInteger<1 || userInteger>15)
     {
       System.out.println("please enter a vaild number");
       userInteger=scanner.nextInt();
     }
     
     for(int row = 1 ; row<=userInteger; row++)
     {
       for(int colum = 1; colum<=userInteger; colum++)
       {
         System.out.print("x");
       }
System.out.print("\n");
     }
   }
 }
 

First, we take input from the user. If the user value is less than 1 & greater than 15 the invalid input message will be shown. If the value is valid the square pattern will display. For multiple inputs, we use while loop and in the while loop we give the condition and the condition is user input value, for example, we entered the value 5, then the loop will run 5 times and the output will be like this:

The output of square pattern program

xxxxx
xxxxx
xxxxx
xxxxx
xxxxx

 

Also, learn:


Leave a Reply

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