Examveda

How do you create a vector containing the first 5 prime numbers in R using a while loop?

A. primes <- numeric(5); num <- 2; while (length(primes) < 5) { if (all(num %% 2:(num-1) != 0)) { primes <- c(primes, num) } num <- num + 1 }

B. primes <- while (length(primes) < 5) { if (all(num %% 2:(num-1) != 0)) { c(primes, num) } num <- num + 1 }

C. primes <- c(2, 3, 5, 7, 11); while (length(primes) < 5) { primes <- c(primes, primes[length(primes)] + 2) }

D. primes <- numeric(5); for (i in seq(2, 11, by = 2)) { primes <- c(primes, i) }

Answer: Option A


Join The Discussion

Related Questions on Control Structures in R Programming

In R, what is the purpose of the if-else statement?

A. To execute a block of code if a condition is true, otherwise execute another block of code

B. To create a loop that iterates a specified number of times

C. To check multiple conditions sequentially

D. To execute a block of code repeatedly until a condition is met