Reputation: 31
Sorry, i have a question on For loop.
Now there're two different loop coding, and my goal is to create a factorial via a function of for loop.
----------------------------------
Method 1
s<-function(input){
stu<-1
for(i in 1:input){
stu<-1*((1:input)[i])
}
return(stu)
}
----------------------------------------
Method 2
k <- function(input){
y <- 1
for(i in 1:input){
y <-y*((1:input)[i])
}
return(y)
}
But 1 result is
> s(1)
[1] 1
> s(4)
[1] 4
> s(8)
[1] 8
and 2 result is
> k(1)
[1] 1
> k(4)
[1] 24
> k(8)
[1] 40320
-------------------------------
It's obviously that 2 is correct, and 1 is incorrect. But why? what's different between 1 and 2? Why i can't use stu<-1*((1:input)[i])
instead of stu<-stu*((1:input)[i])
?
Upvotes: 1
Views: 860
Reputation: 153
it's because the variable stu
is not updating within the for
loop.
s<-function(input){
stu<-1
for(i in 1:input){
stu<-1*((1:input)[i])
message(paste(i,stu,sep="\t"))
}
return(stu)
}
s(5)
1 1 # at the first loop, 1 x 1 is calculated
2 2 # at the 2nd loop, 1 x 2 is calculated
3 3 # at the 3rd loop, 1 x 3 is calculated
4 4 # at the 4th loop, 1 x 4 is calculated
5 5 # at the 5th loop, 1 x 5 is calculated
[1] 5
However, if you use stu<-stu*((1:input)[i])
instead of stu<-1*((1:input)[i])
then the result shows following :
s(5)
1 1 # at the first loop, 1 x 1 is calculated.
2 2 # at the second loop, 1 x 2 is calculated.
3 6 # at the third loop, 2 x 3 is calculated.
4 24 # at the fourth loop, 6 x 4 is calculated.
5 120 # at the fifth loop, 24 x 5 is calculated.
Upvotes: 1