While Loop in R
Hi Cyrene,
in the exercise we're tasked with finding the sum of all numbers from i to n.
Our example shows the solution with i = 1, n = 10. So, we're looking for the sum of all numbers from 1 to 10, which is 55 = 1 + 2 + ...+10
Here is the code:
while(i <= n){
sum <- sum + i
i <- i + 1
print(sum)
}
Let's break it down
Line 1 : We compute the sum with a while loop, and the condition i<=n.
Line 2 : Then we compute the current sum, as :sum = sum + i
Line 3 : And we increase our current i with 1.
Line 4 : For convenience we print out the current sum with each iteration
The algorithm terminates when the while condition isn't TRUE anymore. Hence, when i becomes 11. Leaving us with what we wanted from the beginning: the sum of all numbers from i to n.
Best,
Eli