I'm doing a repeat loop in connection with a question that I am working on: "Set i to be 1. Write a repeat() loop which doubles i until i is greater than 100. What value is i now?"
Here's my code so far
i <- 1
repeat{
print(i)
i <- i*2
if(i > 100) break
}
I ran the above code and got the following output
[1] 1
[1] 2
[1] 4
[1] 8
[1] 16
[1] 32
[1] 64
Now I am just wondering if the above code and output are right? If not, can anyone help me with this one and what am I doing wrong?
You certainly have most of the elements required by the question. Here is one thought: what is meant by "what value is i now?" Does that mean right before the break? Or does it mean after the repeat exits? If it is after the exit, then you need another print statement after the repeat ends. If they want to know the value before the break, you need a print statement after the condition test.
In addition to Harlan’s comment, the question statement “[a] loop which doubles i until i is greater than 100” is also ambiguous. It could mean either of two things:
These two interpretations won’t give a different final value in this particular case but result in different code (and if the code inside the loop were more complex, the result might differ). You are implementing the first variant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With