To print a Hollow Diamond Pattern in R, we use loops and conditional statements to manage spaces and stars.
In this example,
# Print Hollow Diamond Pattern in R
print_hollow_diamond <- function(num_rows) {
for (row in 1:num_rows) {
cat(paste(rep(' ', num_rows - row), collapse = ''), sep = '')
if (row == 1) {
cat('*')
} else {
cat('*')
cat(paste(rep(' ', 2 * row - 3), collapse = ''), sep = '')
cat('*')
}
cat('\n')
}
for (row in (num_rows - 1):1) {
cat(paste(rep(' ', num_rows - row), collapse = ''), sep = '')
if (row == 1 || row == num_rows) {
cat('*')
} else {
cat('*')
cat(paste(rep(' ', 2 * row - 3), collapse = ''), sep = '')
cat('*')
}
cat('\n')
}
}
print_hollow_diamond(5)
* * * * * * * * * * * * * * * *
In this tutorial, we learned How to print Hollow Diamond Pattern in R language with well detailed examples.