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)
}
}
whilewithforloop. May be you just needfor(i in a) if(i < 2) print(i)while, you may increment the index likeflag <- TRUE; i <- 1; while(flag) { print(a[[i]]); i <- i + 1; if(a[[i]] == 2) { flag <- FALSE; }or usebreakstatement }1? Are you trying to iterate over the list and print them until you reach2? Then it seems you need one loop, eitherfororwhile, not both.