878906. Print Square Wall Using Nested Loops
Easy
Print Square Wall Using Nested Loops
Summary
The problem requires you to print a square wall using nested loops. The goal is to print a square shape with asterisks (*) using a specific pattern, where each row and column has the same number of asterisks.
Detailed Explanation
To solve this problem, we can use nested loops to iterate over the rows and columns of the square. We start by initializing an integer variable n to represent the size of the square. Then, we use two nested loops: one for the rows and another for the columns.
Here's a step-by-step breakdown of the solution:
- Initialize an integer variable
nto represent the size of the square. - Use a loop to iterate over each row in the square:
- For each row, use another loop to iterate over each column.
- Print an asterisk (*) for each column, except for the first and last columns (which should be blank).
- After each row is printed, print a newline character to move to the next line.
Here's an ASCII art diagram of the output:
*
* *
* * *
* * * *
* * * * *
The time complexity of this solution is O(n^2), where n is the size of the square. The space complexity is O(1), as we only need a constant amount of space to store the variables.
Optimized Solutions
Java
public class PrintSquareWall {
public static void main(String[] args) {
int n = 5; // Size of the square
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 || j == 0 || i == n - 1 || j == n - 1) {
System.out.print("* ");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}