Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)
edited by

In the below line of code, I just want to understand the working of the code:

while (statement 1){

  ......

  ......

  if (statement 2){

    x <- x + 1

    break

  }

  if (statement 3){

    y <- y + 1

  }

}

1 Answer

0 votes
by (108k points)

See when you are having while(TRUE) in R programming then it makes it run for an infinite time. You can verify how it works with the following code:

num <- 2

x <- 0

y<- 0

while (TRUE){

   if (num % 10 == 0){

     cat('\nprinting from 1: ', num)

      x <- x + 1

      break

    }

   if (num % 2 == 0){

     cat('\nprinting from 2: ', num)

     y <- y+ 1

   }

   num <- num + 1

}

#printing from 2:  2

#printing from 2:  4

#printing from 2:  6

#printing from 2:  8

#printing from 1:  10

x

#[1] 1

y

#[1] 4

Every time the num%2==0 then the y will get incremented and when num==0, then it increments the y and the while loop breaks.

Related questions

Browse Categories

...