1st Class
1st Class
Salma Akter
Lecturer, Department of Statistics
Jagannath University
for loop
• Syntax:
for ( variable in vector) {
statement(s)
}
Ex: 1
for ( i in 1:5) {
print(i^2)
}
for loop
• Ex: 2
storage <-numeric()
for ( i in 1:5) {
storage[i]<-i^2
}
storage
> mean (storage)
• Ex :3
for ( i in 1:3) {
for ( j in 1:2){
print(i+j)
}
}
for loop
• Ex:2
x<-1
while(x<10){
x<-x+1
print(x)
}
while loop
Ex:6 Write R code using while loop that gives the output like
1 1
1 2
2 1
2 2
Solution:
i<-1
while(i<=2){
j<-1
while(j<=2){
print(c(i,j))
j<-j+1
}
i<-i+1
}
while loop
#### Write R code using while loop that gives the output like
1 1
1 3
3 1
3 3
next Statement:
next statement is used to skip one step if while loop
Ex:
x<-1
while(x<7){
x<-x+1
if(x==3)
next
print(x)
}
repeat loop
• Another looping structure is repeat, which repeats the
same expression. The syntax is:
repeat{
statement(s)
if(condition) {
break
}
}
Ex: Finding first 5 natural numbers
x<-1
repeat{
print(x)
x=x+1
if(x==6){
break
}
}
repeat loop