1. LON-CAPA Logo
  2. Help
  3. Log In
 

Browsing resource, all submissions are temporary.


Control Structures and Logic

a. Suppose I create a vector x <- 1:120. Then I decide to set all values in 'x' greater than 78 to 0. I write the following code, but get a warning message and it doesn't do anything to 'x'. What is wrong with the code?

if(x > 78) {
        x <- 0
}






 Tries 0/1

b. Suppose I want to calculate the value of 1 + 1/2 + 1/3 + ··· + 1/100. I write the following code, but it doesn't seem to work. What's wrong with the code? (try to figure out the answer without running the code first)

x <- 0
i <- 1
while(i <= 100) {
        x <- x + 1/i
}






 Tries 0/1

c. In the following code, what will be returned by the last command?

x <- c(1,5,10,10,5,1)
y <- c(10,5,1)
x == y






 Tries 0/1

d. Suppose x is an integer vector of length 366. Each element in x is an integer between 1 and 365. Consider the following code:

for (n in 2:366) {
   if (any(x[1:(n-1)]==x[n])) {
      break
   }
}
print(n)

What does this code do?





 Tries 0/2

Hint: If you find it hard to figure out, try assigning x to some specific values and run the code. For example, try x <- c(1:365,34) and x <- c(rep(1:7,52),105,218) and see what you'll get. Which of the answers above seem to match the outputs? Once you identify a possible correct answer, try running the code with x <- sample.int(365, 366, replace=TRUE), which draws 366 integers randomly between 1 and 365 with replacement and assigns them to x. Is the result consistent with the possible correct answer?