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.
Ask
Anybody can ask a question
Answer
Anybody can answer
Vote
The best answers are voted up and moderated by our team

While Loop in R

While Loop in R

Super Learner
0
Votes
1
Answer

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
0
Votes

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