Understanding For Loops.

Hey. I am currently learning how to code in R and have come across a problem in understanding for loop. This is in regards to creating a loop for the sum of value of n from 1:25. I have understood what the function "compute_s_n" stands for but am unable to understand the for loop code it's used in. The code is as follows:

m <- 25
s_n <- vector(length = m)
for(n in 1:m){
s_n[n] <- compute_s_n(n)
}

In the above "compute_s_n" is a function with the code:

compute_s_n <- function(n){
x <- 1:n
sum(x)
}

compute_s_n <- function(n){
  x <- 1:n
  sum(x)
}

m <- 25
s_n <- vector(length = m)
for(n in 1:m){
  cat("\n","n is ",n ," ** ",sep = "")
  s_n[n] <- compute_s_n(n)
  cat("compute_s_n(",n,") is ",compute_s_n(n) ," ** ",sep = "")
  cat("s_n[",n,"] is ", s_n[n] ," ** " ,sep = "")
}

cat is a function that prints the arguments that you pass (pasting them together with the chosen sep-erator. within cat "\n" means make a newline

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.