Reputation: 419
I am trying to write a program using a while loop:
n=50
sum=array(0,n)
sum[1]=0
for(k in 1:n)
{
sum[k+1]=sum[k]+k
while((sum[k+1]-sum[k])<10)
{
print(sum[k+1])
k=k+1
}
}
sample=data.frame(Sum=sum) sample
its showing:
Error in while ((sum[k + 1] - sum[k]) < 10) { :
missing value where TRUE/FALSE needed
Can anyone tell what is wrong with this code?
Upvotes: 1
Views: 11434
Reputation: 96016
In the second iteration sum[k+1] = NA
since it'll be evaluated to:
(sum[2+1]-sum[1])<10
where sum[2+1] = sum[3]
is NA
. So (sum[k+1]-sum[k])<10
will not be evaluated to one of TRUE/FALSE.
Iteration (k) | sum[k+1]-sum[k]
--------------+------------------
1 | sum[2] - sum[1] They're both known
2 | sum[3] - sum[2] What is sum[3]? (NA)
Upvotes: 2