# ------------------------------------------------------------------
# File name: for_loops.R
#
# for loop in R iterates a block of statements with a counter running through
# values in a sequence. Syntax of for loop is:
# for (counter in sequence) {
# statements
# }
#
# Version: 2.1
# Authors: H. Kocak, University of Miami and B. Koc, Stetson University
# References:
# https://www.r-project.org
# ------------------------------------------------------------------
sequence = seq (1, 10)
for(counter in sequence) {
squared = counter * counter
cat("counter = ", counter, "\t", "squared = ", squared, "\n" )
}
# In the following more complicated example of for loop, we will compute 10 generations of
# a population growing according to the discrete logistic model and save the
# population densities as a vector
cat("Densities of generations with discrete logistic growth model \n")
# Initialize vector holding population densities; x[1] = 0.2
x = 0.2
cat("generation =", 1, "\t", "population density =", x[1], "\n" )
# Growth rate
r = 2.45
number_of_generations = 10
for(i in 1:(number_of_generations - 1)) {
x[i+1] = r*x[i] * (1.0 - x[i])
cat("generation =", i+1, "\t", "population density =", x[i+1], "\n" )
}
# To see x as a vector
print (x)