1

If I have the following for loop:

for (int k = 1; k<n; k=k+1){
    (CODE)
}

and I defined n elsewhere, does the code inside the for loop happen each time k becomes k+1, or does it happen only when k=n?

2 Answers 2

1

assuming n is in scope as control reaches the for loop and is greater than k, the code that represents the body of the loop will execute exactly n - 1 times in this case.

why? unless stated otherwise, after each iteration, k is incremented by 1 (per k = k + 1) and the loop keeps iterating until the condition k < n becomes false (i.e., when k is greater than or equal to n).

see the short on loops for more info: http://youtu.be/rBEwCpvwdPY!

1

Basically, the (CODE) will run as long as k<n. int k =1 will set k = 1 when this part of the code is executed the first time. Once the loop has run, the k=k+1 part of the code will excecute

A good way to show how the code runs is as follows:

  1. When this code is reached, k is set to 1 from the int k =1 instruction.

  2. Then , k<n is checked. If this is true, (CODE) is executed

  3. Then k=k+1 is executed, then return to step 2.

That's one iteration of the loop. Then we go back to step 2 and check k<n. Once k is equal to n (k==n), the loop breaks and the rest of the code runs.

if you understand while loops this may help

int k = 1;

while (k<n)
{
    (CODE)
    k+=1
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .