Explain with an example how break statement is used inside a loop in R.

774    Asked by Uditisingh in Data Science , Asked on Nov 5, 2019
Answered by Uditi singh

Break statement is used to break out of a loop. Let us create a loop and use break to terminate the loop

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

    if(x==10){

        print("x is equal to 10!")

        print("I will also print, woohoo!")

    }

}

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"

[1] "x is equal to 10!"

[1] "I will also print, woohoo!"

Now we will use break on the same loop to observe the difference

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

    if(x==10){

        print("x is equal to 10!")

        break

        print("I will also print, woohoo!")

    }

}

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"

[1] "x is equal to 10!"

Here , the break stopped the iteration before the last sentence “I will also print, woohoo!”



Your Answer

Interviews

Parent Categories