I have the following code snippet where 'b' is an integer array, MAX is an integer and an integer 'ans' stores the result. I'm debugging some code and am not very familiar with C++ as I use Java. The C++ code is:
for(i=0; i<MAX; i++)
ans+=(b[i]!=-1);
The way I have understood it is as:
for(int i=0;i<MAX;i++)
if(b[i]!=-1)
ans+=b[i];
However, I get an absurd answer with the logic above. What does the statement really mean?
I think the Java equivalent is
for(int i=0;i<MAX;i++)
if(b[i]!=-1)
ans++;
In C++, a true statement evaluates to 1. Java does not do that so you have to explicitly increment ans.
Also, note that if MAX is the length of the array (I don't know if it is or not) you can use a for each loop.
for (int a : b)
if (a != -1)
ans++;
for(i=0; i<MAX; i++)
ans+=(b[i]!=-1);
C/C++ evaluates this (b[i]!=-1) to either 0 or 1. In java, that evaluates to a boolean value (true or false), and Java does not convert booleans to integers automatically. However would is very easy to do on your own.
e.g.
for(i=0; i<MAX; i++)
ans+=(b[i]!=-1) ? 1 : 0;
ought to work just fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With