c++ Repeating Statement

Asked 2 years ago, Updated 2 years ago, 101 views

#include <iostream>
using namespace std;

int main(){
  const int N=3;
  int i,j;
  for(i=0; i < N; i++){
    for(j=i; j < N; j++){
      cout << i << "  " << j << endl;
    }
  }
}

When you go around the first loop, j=1 because j=i and there's a posterior operator here, doesn't it start with j=1?

The first printout I expected (0,1) but (0,0) was printed.

c++ loops operator

2022-09-20 19:53

1 Answers

There are three parts in parentheses in the for statement.

For example, in for(A;B;C){ } A runs only once the for statement starts. After that, look at B and execute part {} if B is true, and if B is false, the for statement ends. C runs after part {} runs when B is true. And then we see if B is true again.

After all, A->(B and parentheses)->C->(B and parentheses)->...Repeat in order of .

If i=0 in the first for statement in the question corresponds to A and the i<N condition corresponding to B is true, {} is executed, and i++ corresponding to C has not yet been executed. Therefore, the value of i that is substituted for j is still 0 at this time.


2022-09-20 19:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.