# create a vector filled with random normal values u1 <- rnorm(30) print("This loop calculates the square of the first 10 elements of vector u1") usq=0 iter=1:10 # this can be changed to whatever you need (or just insert 1:10 where iter is in loop) for(i in iter) { usq[i]<-u1[i]*u1[i] # i-th element of u1 squared into i-th position of usq print(usq[i]) } # nested mymat = matrix(nrow=30, ncol=30) # create a 30 x 30 matrix (of 30 rows and 30 columns) for(i in 1:dim(mymat)[1]) # for each row { for(j in 1:dim(mymat)[2]) # for each column { mymat[i,j] = i*j # assign values based on position: product of two indexes } } i.val=1:5 j.val=1:5 mymat[i.val,j.val] i.val=1:10 j.val=1:10 mymat[i.val,j.val] i.val=1:30 j.val=1:30 mymat[i.val,j.val] # while with a function( ) readinteger <- function() { n <- readline(prompt="Please, enter your ANSWER: ") } response<-as.integer(readinteger()) while (response!=42) { print("Sorry, the answer to whatever the question MUST be 42"); response<-as.integer(readinteger()); } # repeat loop readinteger <- function() { n <- readline(prompt="Please, enter your ANSWER: ") } repeat { response<-as.integer(readinteger()); if (response==42) { print("Well done!"); break } else print("Sorry, the answer to whatever the question MUST be 42"); }