# for loop in R comparison

The following piece of code does exactly what I need. However, for exercise purposes, I cannot use the `rep` function.

``````for (i in 1:4){
print(paste(rep(LETTERS[i], i), collapse = ""))
}
``````
•  "A"
•  "BB"
•  "CCC"
•  "DDDD"

So I attempted the following:

``````for (i in 1:4) {
for (j in 1:i) {
print(paste(LETTERS[i]))
}
cat('\n')
}
``````
•  "A"

•  "B"

•  "B"

•  "C"

•  "C"

•  "C"

•  "D"

•  "D"

•  "D"

•  "D"

which isn’t quite the output that I’m going for. I tried transposing within the inner for loop all to no avail. Can someone please help here?

### >Solution :

One potential solution would be to add each letter to a vector then print the vector after each "j" loop and clear the vector, e.g.

``````output <- c()
for (i in 1:4) {
for (j in 1:i) {
output <- paste0(output, LETTERS[i])
}
print(output)
output <- c()
}
#>  "A"
#>  "BB"
#>  "CCC"
#>  "DDDD"
``````

Created on 2023-06-28 with reprex v2.0.2

## Edit

Per @thelatemail’s comment, you should avoid ‘growing’ a vector in the ‘lazy’ way I suggested above, as performance is terrible. A much better option is to pre-allocate the vector then fill it, with letters and collapse the output e.g.

``````for (i in 1:4) {
out <- vector("character", i)
for (j in 1:i) {
out[j] <- LETTERS[i]
}
print(paste(out, collapse=""))
}
#>  "A"
#>  "BB"
#>  "CCC"
#>  "DDDD"
``````

Created on 2023-06-28 with reprex v2.0.2