878901. Print Square
Basic
Print Square
Slug: print-square--105330
Difficulty: Basic
Id: 878901
Topic Tags: python-conditionals, python-loops, CPP, Java
Summary
Print Square is a basic problem that involves printing a square pattern of asterisks (*) based on the given input. The problem requires you to create an algorithm that prints a square with side length n where n is the user's input.
Detailed Explanation
The problem can be solved by using nested loops. The outer loop controls the number of rows, while the inner loop controls the number of columns. We use conditionals to check if we're at the edge of the square and adjust our printing accordingly.
Here's a step-by-step breakdown of the solution:
- Initialize an integer variable
nto store the side length of the square. - Use two nested loops, one for rows and one for columns. The outer loop runs from 0 to n-1, while the inner loop runs from 0 to n-1 as well.
- Inside the inner loop, print asterisks (*) based on the current row and column indices. If we're at the edge of the square (i.e.,
roworcolis equal to 0 or n-1), print a newline character (\n) before printing the remaining characters. - After the loops finish executing, return from the function.
Time complexity: O(n^2) Space complexity: O(1)
Optimized Solutions
Java
public class PrintSquare {
public static void main(String[] args) {
int n = 5; // example input
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 || i == n - 1 || j == 0 || j == n - 1) {
System.out.print("* ");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}