Question about for-loop

Hi all.
the code below try to use for-loop nest, questions are:

  1. when i=2, DO A, does the i(=2) continue go through the code after DO A (still working at DO B? the DO B need it), or just finish at DO A?
  2. is the nest DO C used here OK, or should try not to use for-loop nest?

Thanks
Adam

for (int i = 0, i < T, i++) {

  if (i == 2) {
    //DO A;
  }

  //DO B;

  if (i == 5) {
    for (int j = 0; j < T1, j ++) {
      //DO C;
    }
  }
}

The for loops are broken.

for (int i = 0; i < T; i++) { // semi-colon  ; NOT comma  ,
}

and

for (int j = 0; j < T1; j++) { // semi-colon ; NOT comma  ,
}

After the for loops are fixed,

DO A happens when i is 2.

DO B happens when i is 0 to T - 1.

DO C happens when i is 5 and when j is 0 to T1 - 1.

1 Like

Thank you.
sorry for the typo.

Just to maybe open your eyes:

A for loop controls the execution of one statement.

Which might be a simple statement or an { embraced block }.

Within any block of code - you've seen them all your life, a function is a block of statements, for example - you can have as many statements you want, and they will be executed in sequence, like usual.

Any of those statements might be a simple statement or… an { embraced block }.

So there's nothing magic or any need to wonder if the second if statement gets executed, no need to wonder if it is OK to have a for loop inside a for loop...

Where would we be if there were such things to worry about alla time?

a7

1 Like

Great.
Thank you.

Can be seen as...

  if (i == "It is raining") {
    for (j = "go outside"; j = until "return inside"; "play in the rain"++) {
      "wear boots";
    }
  }
1 Like

Great.
Thank you.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.