I'm doing an exercise in java about while loops and I don't understand why in the solution the save of the while loop uses "!cond". If you can help me I would appreciate it. The statement is as follows:
Given an array of integers, check if there are three consecutive numbers between three consecutive positions in the array ; if it is chao, it should return the position where the sequence starts, or -1 if it doesn't exist.
The solution of the exercise is:
/** Devuelve el indice en donde comienza
* la primera secuencia de tres valores
* seguidos, -1 si no existe */
public static int secTres(int[] a) {
boolean cond = false;
int i = 0;
while (i < a.length - 2 && !cond) {
if (a[i + 1] == a[i] + 1 &&
a[i + 2] == a[i + 1] + 1) {
cond = true;
} else { i++; }
}
if (cond) { return i; }
else { return -1; }
}
The symbol ! is a unary logical negation operator, which negates the value of a Boolean expression. This operator changes the value from True to False , and from False to True .
On the other hand, the while statement executes a block of statements as long as the while expression is True .
Now in your example, you have something like this:
Your doubt is that if the variable cond is initialized to False , when it is negated in the while loop it should be True , but it really isn't and it has nothing to do with one thing with the other.
The instruction:
It translates into Spanish as "as long as the cond variable is True do something" and let's say that it is a kind of "shortening" of the syntax:
As you can see in the first way you write fewer words.
The instruction:
It translates into Spanish as "as long as the value of the cond variable is False , do something", and its equivalent is:
All of these are resources offered by programming languages so that programmers write less, it's up to you to choose which of the two forms you like more and use it, it's a matter of taste, if the short form confuses you, then use the long form.
I recommend that you research the term sugar syntax or syntactic sugar on the Internet , it basically consists of what I explained above, that is, writing code using the least amount of words.
If
a[i + 1] == a[i] + 1 && a[i + 2] == a[i + 1] + 1
it is true, thencond
it is changed to true.In the while one of the conditions is that
cond
it be false, so if point 1 is met, the while no longer meets and continues to the if where it returns the index of the array.Actually, if we remove that !cond from the while the method would still work correctly. The reason why there is that !cond in the while is to avoid doing more operations of the account.
First of all you have a boolean to false. If the condition of the if within the while is met, that boolean becomes true indicating that you have found the number, so it is not necessary to continue iterating. That's why it's part of the while condition. Then it goes to the last if to validate if the condition has been met and return the number.