Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

r - Can somebody help me understand "for" functions?

For a homework question I have the following code:

Could someone explain me what is happening in the code, and why it results in 22?

k <- 1    
for (i in 1:3){    
  k <- k + 1  
  for (j in 1:2){
    k = k * j
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

An easy way to understand how loops work in any programming language is to follow, step by step what it is doing.

Here a simple example of how you can "debug" in paper. This could be useful in the future.

The table below represents each iteration of your loops and the values of each operation.

You should read it in this way:

  1. Initially k = 1;
  2. In the first iteration of the outer loop k becomes the current value of k (1) + 1, so k = 2.
  3. Then the inner loop makes its first iteration, then j = 1 and k = k (2) * j (1), so k = 2
  4. Then the second iteration of inner loop, j becomes 2 and k is still 2, so k = k (2) * j (2) so k = 4
  5. Then returns to the outer loop where i becomes 2 and k = k (4) + 1 => k = 5
  6. Then start again the inner loop (repeat steps 3 and 4)

and repeat until i is 3.

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...