To print a pyramid pattern in R, you can use nested loops where the outer loop controls the rows and the inner loops control the spaces and stars printed in each row.
In this example,
printPyramid
that takes an integer n
as input to represent the number of rows in the pyramid.cat()
to print the row.printPyramid <- function(n) {
for (i in 1:n) {
cat(paste(rep(' ', n - i), collapse = ''),
paste(rep('*', 2 * i - 1), collapse = ''),
'\n', sep = '')
}
}
printPyramid(5)
* *** ***** ******* *********
In this tutorial, we learned How to print Pyramid Pattern in R language with well detailed examples.