Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to Print Square Star Pattern
In this article, we will understand how to print square star pattern. The pattern is formed by using multiple for-loops and print statements.
Below is a demonstration of the same −
Input
Suppose our input is −
Enter the length of a side : 8
Output
The desired output would be −
The square pattern : * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Algorithm
Step 1 - START Step 2 - Declare three integer values namely i, j and my_input Step 3 - Read the required values from the user/ define the values Step 4 - We iterate through two nested 'for' loops to get space between the characters. Step 5 - After iterating through the innermost loop, we iterate through another 'for' loop. This will help print the required character. Step 6 - Now, print a newline to get the specific number of characters in the subsequent lines. Step 7 - Display the result Step 8 - Stop
Example 1
Here, the input is being entered by the user based on 8a prompt. You can try this example live in our coding ground tool
.
import java.util.Scanner;
public class SquarePattern{
public static void main(String args[]){
int i, j, my_input;
System.out.println("Required packages have been imported");
Scanner my_scanner = new Scanner(System.in);
System.out.println("A reader object has been defined ");
System.out.print("Enter the length of a side : ");
my_input = my_scanner.nextInt();
System.out.println("The square pattern : ");
for(i = 1; i <= my_input; i++){
for(j = 1; j <= my_input; j++){
System.out.print("*");
}
System.out.print("\n");
}
}
}
Output
Required packages have been imported A reader object has been defined Enter the length of a side : 8 The square pattern : * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Example 2
Here, the integer has been previously defined, and its value is accessed and displayed on the console.
public class SquarePattern{
public static void main(String args[]){
int i, j, my_input;
my_input = 8;
System.out.println("The length of a side is defined as " +my_input);
System.out.println("The square pattern : ");
for(i = 1; i <= my_input; i++){
for(j = 1; j <= my_input; j++){
System.out.print("* ");
}
System.out.print("\n");
}
}
}
Output
The length of a side is defined as 8 The square pattern : * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Advertisements