To print a Hollow Square Pattern in R, you can use nested loops. The outer loop controls the rows, and the inner loop controls the columns. Conditions are used to determine whether to print stars or spaces for the pattern.
In this example,
printHollowSquare
that takes the side length n
as a parameter.for
loops, one for rows and one for columns, to iterate through each cell of the square.*
) for the border and spaces (
) for the inside.printHollowSquare
with the desired side length to print the pattern.printHollowSquare <- function(n) {
for (i in 1:n) {
row <- ''
for (j in 1:n) {
if (i == 1 || i == n || j == 1 || j == n) {
row <- paste0(row, '*')
} else {
row <- paste0(row, ' ')
}
}
cat(row, '\n')
}
}
sideLength <- 5
printHollowSquare(sideLength)
* * * * * * * * * * * * * * * *
In this tutorial, we learned How to print Hollow Square Pattern in R language with well detailed examples.