Explain how while loop works in R.

793    Asked by Tanyaverma in Data Science , Asked on Jan 6, 2020
Answered by Tanya verma

while loops are a while to have your program continuously run some block of code until a condition is met (made TRUE). The syntax is:

while (condition){

    # Code executed here

    # while condition is true

}

For explaining while loop let us assign a variable

We'll be using the cat function in the next example which shows how a while loop works:

x <- 0

while(x < 10>

    cat('x is currently: ',x)

    print(' x is still less than 10, adding 1 to x')

    # add one to x

    x <- x+1

}

Output

x is currently: 0[1] " x is still less than 10, adding 1 to x"

x is currently: 1[1] " x is still less than 10, adding 1 to x"

x is currently: 2[1] " x is still less than 10, adding 1 to x"

x is currently: 3[1] " x is still less than 10, adding 1 to x"

x is currently: 4[1] " x is still less than 10, adding 1 to x"

x is currently: 5[1] " x is still less than 10, adding 1 to x"

x is currently: 6[1] " x is still less than 10, adding 1 to x"

x is currently: 7[1] " x is still less than 10, adding 1 to x"

x is currently: 8[1] " x is still less than 10, adding 1 to x"

x is currently: 9[1] " x is still less than 10, adding 1 to x"


While can also be used with a for loop to build a function and other functions such as break, continue or pass can also be added while iterating a function using for or while loop.



Your Answer

Interviews

Parent Categories