Everyone found an easy way for pattern printing in other programming languages. But its a tough task using R language . This article focuses on drawing various patterns using R language and its constructs.
Approach
- Start first loop for number of lines
- Start second loop for item to be displayed
- Print item
- Increment second loop until a condition is reached
- Increment first loop until condition is true
- Continue in this fashion
Program 1: Drawing a Triangle with numbers
R
stars = c ()
for (i in 1:5){
for (j in 1:i+1){
stars = c (stars, i)
}
print (stars)
stars = c ()
}
|
Output:
[1] 1
[1] 2 2
[1] 3 3 3
[1] 4 4 4 4
[1] 5 5 5 5 5
Program 2: Drawing a triangle with *
R
stars = c ()
for (i in 1:5){
for (j in 1:i+1){
stars = c (stars, "*" )
}
print (stars)
stars = c ()
}
|
Output:
[1] "*"
[1] "*" "*"
[1] "*" "*" "*"
[1] "*" "*" "*" "*"
[1] "*" "*" "*" "*" "*"
Program 3: Draw inverted triangle
R
starsrev = c ()
i=1
j=5
while (i<=5){
for (j in 1:j){
starsrev = c (starsrev, "*" )
}
print (starsrev)
starsrev = c ()
i=i+1
j=j-1
}
|
Output:
[1] "*" "*" "*" "*" "*"
[1] "*" "*" "*" "*"
[1] "*" "*" "*"
[1] "*" "*"
[1] "*"
Program 4: Drawing inverted as well as normal triangle pattern
R
i=1
stars = c ()
while (i<=5){
for (j in 1:i+1){
stars = c (stars, "*" )
}
print (stars)
stars = c ()
i=i+1
}
starsrev = c ()
i=1
j=5
while (i<=5){
for (j in 1:j){
starsrev = c (starsrev, "*" )
}
print (starsrev)
starsrev = c ()
i=i+1
j=j-1
}
|
Output:
[1] "*"
[1] "*" "*"
[1] "*" "*" "*"
[1] "*" "*" "*" "*"
[1] "*" "*" "*" "*" "*"
[1] "*" "*" "*" "*" "*"
[1] "*" "*" "*" "*"
[1] "*" "*" "*"
[1] "*" "*"
[1] "*"
Last Updated :
03 Mar, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...