The 365 Data Science team is proud to invite you to our own community forum. A very well built system to support your queries, questions and give the chance to show your knowledge and help others in their path of becoming Data Science specialists.
Anybody can ask a question
Anybody can answer
The best answers are voted up and moderated by our team

While Loop in R

While Loop in R


I would like help understanding the solution to the exercise given for this lecture. More specifically, I do not understand the second body of code.

1 Answer

365 Team

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
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.


Complete Data Science Education
Get 50% OFF