Reputation: 45
learning c++ and I'm sure I'm overlooking something obvious but I'm not sure why I dont get a message that i == j even though after the 3rd iteration the numbers are the same ?
This is the output:
8 is not equal to 12
9 is not equal to 11
appreciate any hints!
#include<iostream>
int main(){
int i=8;
int j=12;
for (i,j; i!=j; ++i, --j)
{
if (i == j)
{
std::cout << "i = j" << "\n"; // this part doesnt work
break;
}
else
std::cout << i <<" is not equal to " << j <<"\n";
}
}
Upvotes: 0
Views: 948
Reputation: 310980
The loop is executed only when i
is not equal to j
due to the condition
for (i,j; i!=j; ++i, --j)
^^^^
When i
is equal to j
the body of the loop does not get the control because the condition evaluates to false
.
You should change the condition in the loop. Also the break
statement is redundant.
Here is a demonstrative program.
#include <iostream>
int main()
{
for ( int i = 8, j = 12; not ( j < i ); ++i, --j )
{
if ( i == j )
{
std::cout << "i = j" << "\n";
}
else
{
std::cout << i <<" is not equal to " << j <<"\n";
}
}
}
Its output is
8 is not equal to 12
9 is not equal to 11
i = j
Pay attention to that in any case in general you may not use the condition i != j
in the loop because when this range contains an even number of values when you can get an infinite loop. For example consider the case when i
is equal to 10
and j
is equal to 11
. In this case after the first iteration of the loop i
will be equal to 11
and j
will be equal to 10
and again i != j
.:)
Upvotes: 2
Reputation: 482
That's because your loops stops when i
is equal to j
, before ever printing it out. And since you break out of your loop when i
is supposed equal to j
, you can rewrite it like this:
for (int i = 8, j = 12; i != j; ++i, --j)
std::cout << i << " is not equal to " << j << "\n";
std::cout << "i = j\n";
Upvotes: 0
Reputation: 7726
You could have used for (; i <= j; ++i, --j)
.
The following is modified version of your code, just changed from !=
to <=
:
#include <iostream>
int main()
{
int i = 8;
int j = 12;
for (; i <= j; ++i, --j)
{
if (i == j)
{
std::cout << "i = j" << std::endl;
}
else
std::cout << i << " is not equal to " << j << "\n";
}
return 0;
}
Output:
8 is not equal to 12
9 is not equal to 11
i = j
Upvotes: 1