Open In App

Nested for Loop to Print a Pattern.

A nested for loop in R is used when we want to iterate through multiple dimensions, such as rows and columns of a matrix, or for creating patterns. we will discuss how to print multiplication tables up to a certain number with its working example in the R Programming Language using R for loop conditions. Everyone found an easy way for pattern printing in other programming languages. But it’s a tough task using the R language

Approach:

Syntax:

for (i in 1:n) {
for (j in 1:m) {
# Pattern generation logic
}
}

Example 1: Printing a right-angle triangle




n <- 5
for (i in 1:n) {
  for (j in 1:i) {
    cat("* ")
  }
  cat("\n")
}

Output:



* 
* *
* * *
* * * *
* * * * *

Example 2: Printing a rectangular pattern




n <- 4
m <- 6
for (i in 1:n) {
  for (j in 1:m) {
    cat("* ")
  }
  cat("\n")
}

Output:

* * * * * * 
* * * * * *
* * * * * *
* * * * * *

Example 3: Draw inverted triangle




star = c()
i=1
j=5
 
while(i<=5){
for(j in 1:j){
    star = c(star, "*")
}
     
print(star)
     
star = c()
 
i=i+1
j=j-1
}

Output:



[1] "*" "*" "*" "*" "*"
[1] "*" "*" "*" "*"
[1] "*" "*" "*"
[1] "*" "*"
[1] "*"

Article Tags :