1

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?

Maroun
  • 94,125
  • 30
  • 188
  • 241
user2458552
  • 419
  • 2
  • 5
  • 17
  • what is array ? method ? – KOTIOS Jun 22 '13 at 07:26
  • You're modifying your `for` loop counter `k` inside the loop. You probably don't really want to do this. – Hong Ooi Jun 22 '13 at 07:30
  • What would be an approach to write this program then given that I have to write it using the while statement that I have written.Any suggestion would be of immense help.Thanks! – user2458552 Jun 22 '13 at 07:39
  • possible duplicate of [Error In R: Missing Value where TRUE/FALSE needed](http://stackoverflow.com/questions/7355187/error-in-r-missing-value-where-true-false-needed) – Richie Cotton Dec 26 '14 at 16:14

1 Answers1

2

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)
Maroun
  • 94,125
  • 30
  • 188
  • 241
  • But k in the second iteration is 2 right.SO,when we enter the forloop its first calculating sum[2+1]=sum[2]+2 – user2458552 Jun 22 '13 at 07:37
  • No, you're still in the `while` loop, you still didn't calculate `sum[3]` which will be evaluated in the `while` loop. – Maroun Jun 22 '13 at 07:38
  • What would be an approach to write this program then given that I have to write it using the while statement that I have written.Any suggestion would be of immense help.Thanks! – user2458552 Jun 22 '13 at 07:40
  • You can remove the `for` loop, initialize the first two elements, and write `sum[k+1]=sum[k]+k` in the body of the `while` loop. – Maroun Jun 22 '13 at 07:42
  • n=50 sum=array(0,n) sum[1]=0 sum[2]=1 k=1 while((sum[k+1]-sum[k])<10) { sum[k+1]=sum[k]+k print(sum[k+1]) k=k+1 } } you mean this??but in the second iteration when k=2,sum[2+1] will be NA – user2458552 Jun 22 '13 at 07:48
  • It won't be NA since before you enter the `while` loop it'll have the value of `sum[2] + 2`. – Maroun Jun 22 '13 at 07:50
  • n=50 sum=array(0,n) sum[1]=0 sum[2]=1 k=1 while((sum[k+1]-sum[k])<10) { sum[k+1]=sum[k]+k print(sum[k+1]) k=k+1 } its showing Error in while ((sum[k + 1] - sum[k]) < 10) { : missing value where TRUE/FALSE needed – user2458552 Jun 22 '13 at 07:54
  • Try to place `k = k + 1` in the first line in the loop. – Maroun Jun 22 '13 at 07:57