Unlike Program 41 (square pyramid), this pattern visits every cell and decides with a simple border check — total cells for size n is n².
Approach
How to Solve It
Loop rows and columns from 1 to n. Append "1 " on the border; otherwise append two spaces. End each row with console.log.
Method
Idea
Best for
Border if
i === 1 || i === n || j === 1 || j === n
Classic hollow square
Other char
Same check; append "* " instead of "1 "
Star-border demos
Pseudocode
Pseudocode
for i from 1 to n:
line = ""
for j from 1 to n:
if i is 1 or i is n or j is 1 or j is n:
append "1 "
else:
append " "
print line
Cheat sheet
Goal
Pattern
Outer (rows)
for (let i = 1; i <= n; i++)
Inner (cols)
for (let j = 1; j <= n; j++)
Border test
i === 1 || i === n || j === 1 || j === n
Border cell
line += "1 ";
Interior cell
line += " ";
End the row
console.log(line);
Printing Numbers vs Starting a New Line
API
Effect
Use for
line += …
Stays on the same row
Each cell ("1 " or " ")
console.log(line)
Ends the current row
After all columns in the row
Append without a newline, then end the row once.
Try it
Live Preview
Change the square size and the hollow border updates instantly.
Whole numbers from 2 to 12. Tap a chip or type a value — the preview redraws as you go.
Live resultn = 5 · 25 cells
1 1 1 1 1
1 1
1 1
1 1
1 1 1 1 1
Trace
Worked Walkthrough
Trace three rows when n = 5 — watch which cells get 1 vs spaces.
Row i
Border cells
Interior
Printed row
1
all j (top)
none
1 1 1 1 1
2
j=1, j=5
j=2..4 spaces
1 1
5
all j (bottom)
none
1 1 1 1 1
Middle rows only light the left and right edges; top and bottom fill every column.
Code
JavaScript Programs
Three complete programs: fixed n = 5, prompt input, and an asterisk border. Use View Output for samples, or Try It Yourself to edit and run live.
Example 1 — Fixed n = 5
Hard-coded size — border check, "1 " on edges, two spaces inside.
JavaScript
const n = 5;
for (let i = 1; i <= n; i++) {
let line = "";
for (let j = 1; j <= n; j++) {
if (i === 1 || i === n || j === 1 || j === n) {
line += "1 ";
} else {
line += " ";
}
}
console.log(line);
}
const n = parseInt(prompt("Enter square size (n >= 2):"), 10);
if (!Number.isFinite(n) || n < 2) {
console.log("Please enter an integer n >= 2.");
} else {
for (let i = 1; i <= n; i++) {
let line = "";
for (let j = 1; j <= n; j++) {
if (i === 1 || i === n || j === 1 || j === n) {
line += "1 ";
} else {
line += " ";
}
}
console.log(line);
}
}
1. Prompt and validate. Use parseInt and require n >= 2 for a meaningful hollow frame.
2. Same border core. Only the source of n changes — the if condition matches Example 1.
3. Entering 4. A 4×4 frame: full top/bottom rows, sides only in the middle.
Example 3 — Asterisk Border
Same hollow frame; border cells append "* " instead of "1 ".
JavaScript
const n = 5;
for (let i = 1; i <= n; i++) {
let line = "";
for (let j = 1; j <= n; j++) {
if (i === 1 || i === n || j === 1 || j === n) {
line += "* ";
} else {
line += " ";
}
}
console.log(line);
}