Java program to print square star pattern program. We have written the below print/draw square asterisk/star pattern program in four different ways with sample example and output, check it out. At the end of the program, we added compiler such that you can execute the below codes:
- Print Square Star Pattern – Using For Loop
- Print – Using While Loop
- print – Using Do While Loop
Using Standard Java Program
1 2 3 4 5 6 7 8 9 10 11 12 |
import java.util.Scanner; public class Squarestar { public static void main(String[] args) { for(int i=0;i<5;i++) System.out.println("***** "); } } |
Output:
1 2 3 4 5 |
***** ***** ***** ***** ***** |
Using For Loop
1) Read n value and store it into the variable n
2) The outer loop iterates n times with the structure for(i=0;i<n;i++).
3) The inner loop iterates n times with the structure for(j=0;j<n;j++).
4) The inner loop checks the condition j<n
5) Prints character for n rows and n columns.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import java.util.Scanner; public class Squarestar { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("Enter N : "); int n=sc.nextInt(); System.out.print("Enter Symbol : "); char c = sc.next().charAt(0); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { System.out.print(c); } System.out.println(); } } } |
Output:
1 2 3 4 5 6 7 8 |
Enter N : 5 Enter Symbol : * ***** ***** ***** ***** ***** |
Using While Loop
1) The outer while loop executes iterates until the condition i++<n is false.
2) The inner loop will display the character until the condition j++<n is false for every i value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import java.util.Scanner; public class Squarestar { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("Enter N : "); int n=sc.nextInt(); System.out.print("Enter Symbol : "); char c = sc.next().charAt(0); int i=0; while(i++<n) { int j=0; while(j++<n) { System.out.print(c); } System.out.println(); } } } |
Output:
1 2 3 4 5 6 7 8 9 10 |
Enter N : 7 Enter Symbol : * ******* ******* ******* ******* ******* ******* ******* |
Using Do-While Loop
1) The outer do-while loop iterates until the condition ++i<n is false.
2) The inner loop prints the character until the condition ++j<n is false for each i value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import java.util.Scanner; public class Squarestar { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("Enter N : "); int n=sc.nextInt(); System.out.print("Enter Symbol : "); char c = sc.next().charAt(0); int i=0; do { int j=0; do { System.out.print(c); }while(++j<n); System.out.println(); } while(++i<n) ; } } |
Output:
1 2 3 4 5 6 7 8 |
Enter N : 5 Enter Symbol : . ..... ..... ..... ..... ..... |
More Programs: