Reputation: 118
for loop in c
int i;
int n = 20;
for(i = 0; i + n; i-- ) {
printf("-\n");
}
for loop in java
int i;
int n=20;
for (i = 0; i + n; i--) {
System.out.println("-\n");
}
In the above example for loop in c is working fine(will print "-" 20 times).But for loop in java shows error as
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from int to boolean
why it shows this kind of error?
Upvotes: 3
Views: 3071
Reputation: 85779
In C, 0
is considered false
and the rest of number are interpreted as true
. In Java, this doesn't work since it has a boolean
type that is not an int
, and an int
cannot be directly converted into a boolean
.
To fix the Java code, you should write the second part as a boolean
expression:
for (i = 0; (i + n) != 0; i--) {
System.out.println("-\n");
}
While (i + n) != 0
may work, I would prefer to use (i + n) > 0
, because if n
starts at -1
, this loop will work until i
goes down to Integer.MIN_VALUE
value, underflows to Integer.MAX_VALUE
and go down to 1
. To prevent that behavior (in case is undesired), it would be better to write it like this:
for (i = 0; (i + n) > 0; i--) {
System.out.println("-\n");
}
From @Lundin's comment, looks like your C code should be fixed as well:
//or use my proposed fix by using > rather than !=
for(i = 0; (i + n) != 0; i-- ) {
printf("-\n");
}
Upvotes: 10
Reputation: 79838
The original version of C didn't have booleans, so everyone used integers instead. The language would interpret anything non-zero as true, and zero as false.
But Java is stricter about what's a boolean and what's an integer - you actually need to use a boolean expression (such as i + n != 0
) to check whether the loop should continue.
Upvotes: 3