I have the following code
for (int i = 0; i < 4; i++) {
for (int j = 0; (j < 4) && (j != i); j++) {
cout << j << "," << i;
}
cout << "\n";
}
Output:
(0,1)
(0,2)(1,2)
(0,3)(1,3),(2,3)
I expected it to print all the pairs except the matching ones:
(1,0)(2,0)(3,0) //without (0,0)
(0,1)(2,1)(3,1) //without (1,1)
(0,2)(1,2)(3,2) //without (2,2)
(0,3)(1,3)(2,3) //without (3,3)
and when the condition in the for loop is changed to (j < 4) && (j == i) // output: (0,0)
it only prints (0,0)
instead of all the all the matching pairs. I know it has something to do with &&
but why does it not show other pairs as i expected it to?
I expected it to print all the pairs except the matching ones
Then replace (j < 4) && (j != i)
with j < 4
and add an if
statement inside the inner loop.
The for loop is run until the first time the termination condition turns false. That's why it's called the termination condition.
How an for loop works is you start by initializing a variable. (initialization; ex. i = 1)
Then, the 2nd command is a boolean statement that, when false, will pause the for statement. (ex. i < 10)
The 3rd statement tells the for loop what to do when the boolean statement is true. (ex. increment i, i=i+1)
However, in your condition, you wrote (j < 4) && (j != i), so whenever your j and i are equal, you immediately stop executing the 2nd nested for loop!
You can add an if statement to mitigate this problem, but you can also use the continue statement, which will skip anything after it when the values are equal (without completely stopping the for loop) :
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
if(i == j) continue;
cout << j << "," << i;
}
}
Here's a live demo: https://ideone.com/Q9oe4I
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.