0

I expect the given code to output the answer : 1. However the loop runs forever. I am trying to see if while loop works for such a case. The use of while loop is necessary for the solution.

a = list(1,2,3,4)

for(i in a){
  while(i != 2){
    print(i)
  }
}
4
  • 2
    why do you need a while with for loop. May be you just need for(i in a) if(i < 2) print(i) Commented Apr 2, 2021 at 20:31
  • @akrun I am trying to understand what can be done with while loop. Is it possible to use it in such a case to work? Commented Apr 2, 2021 at 20:32
  • 1
    With while, you may increment the index like flag <- TRUE; i <- 1; while(flag) { print(a[[i]]); i <- i + 1; if(a[[i]] == 2) { flag <- FALSE; } or use break statement } Commented Apr 2, 2021 at 20:47
  • How is the answer supposed to be 1? Are you trying to iterate over the list and print them until you reach 2? Then it seems you need one loop, either for or while, not both. Commented Apr 2, 2021 at 20:53

2 Answers 2

1

Here are two solutions that work with while. The first one with a 'flag' set as TRUE, and the index as 1, based on the condition, set the 'flag' to FALSE

flag <- TRUE
i <- 1
while(flag) {
  print(a[[i]])
  i <- i + 1
  if(a[[i]] == 2) {
   flag <- FALSE
    }

 }
#[1] 1

Or we add a break

i <- 1
while(TRUE) {
  print(a[[i]])
  i <- i + 1
  if(a[[i]] == 2) {
    break
    }

  }
#[1] 1
Sign up to request clarification or add additional context in comments.

Comments

1

The value of i does not change inside the while loop, so you never advance to the next item in list. You need if instead of while:

a = list(1,2,3,4)

for(i in a){
  if(i != 2){
    print(i)
  }
}

2 Comments

I should have stated more clearly, I am looking for an answer that works with a while loop, my apologies. Edited the question
Then specify what needs to happen inside the while loop. If i equals 1, you have an infinite while loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.