In previous episodes we have discussed the notion of control structures. We have seen that they are particular instructions, making it possible to execute processing on the basis of conditions. Also, they allow to repeat processing. Today, we will dig deeper in this topic and tackle another way to repeat processing : the conditional loops. If, in a program, we wish to repeat a processing sequence and that the number of repetitions is known a priori, namely before entering the loop, we have seen that it was possible to resort to "for loops", via the concept of iteration. However, in certains situations, we do not a priori how many times we wish to repeat the processing. Typically, we could want to repeat a processing as long as a condition is verified without knowing how many repetitions will be necessarily required before the condition becomes false. In such a case, we need to resort to another control structure: the conditional loops. They are repetitions which will depend on a condition. In Java, they take the form of "while" loops or "do while" loops. Those are the subject of today's episode. To help you get an idea, we will go back to our example regarding the average of a certain number of grades. We do not know à priori how many grades we will have to calculate the average of. Thus, we start by asking the user to fill us up through keyboard interation. Once the number of grades has been entered, if this number is strictly positive, we will initiate a repetitive process, a "for loop" permitting the input of all these grades, still via keyboard interaction. We will add the newly typed grade to the sum and calculate the average later. Once the number of grades has been reached, once all grades have been entered, we will exit the "for loop", calculate and print the average of the grades. Upon closer inspection, we may find it unnatural to let the user input a number of grades equal to 0. Indeed, it doesn't make much sense. Thus, we are wondering how to compel the user to input a number of grades greater than 0. The underlying idea is to repeat these processing until the user inputs a number of grades strictly positive. The solution to repeat these two lines of instruction as long as the user has not entered a number of grades strictly positive, is to resort to a particular instruction : a "do while" conditional loop. So, how do we write such a control structure ? We use the keyword "do", that is, repeat. And the kekyword "while". What do we wish to repeat ? Actually, we wish to repeat the execution of these two instructions, which are in braces. We will repeat these instructions as long as this condition is true. So, if the user were to input a number of grades less or equal to 0, the evaluation of this condition will return "true". Therefore, we will repeat these processing, entering a new cycle of the loop. Let us examine step by step the execution of such a "do while" instruction. First of all, we declare a variable storing the to-be-entered number of grades. Then, we execute directly the instruction "do while". Here, nothing special, we will execute the so-called loop's body, namely the instructions which will be repeated if need be. Here, we will ask the user to input the number of grades. Let us imagine that they type the value 0. We now reach this line, where the continuation condition will be evaluated. Here, since the number of grades is equal to 0, the condition will be evaluated "true". We will thus enter the loop again, repeating the processing. We thus begin a new cycle of the loop. We ask the user to type a number of grades again. Let us imagine that the user inputs this time, the value minus one. We execute this instruction again, evaluating the continuation condition. Again, since the number of grades is less or equal to 0, the condition will be evaluated as "true". Thus, we will repeat the processing once more. At the third iteration, we will ask the user to input another number of grades. This time, the crestfallen user will understand what is expected of them and input a strictly positive number. Once we reach the instruction evaluating the continuation condition. This time, the evaluation will return "false" since the number of grades is strictly positive. Therefore, we will stop iterating and exit the "do while" loop. Concretely, we will resume with the execution of these processing, at the end of the "do while" loop, signified by this semicolon. Thus, we will execute possible subsequent instructions after the "do while" loop. In this example, we clearly see that it is not possible to forsee how many iterations will be necessary before we can exit the loop. Indeed, the number of repetitions is function of the user's will, which we cannot guess à priori. A "for loop" would thus not have been adapted to the processing we attempt to achieve. Now, let us examine thouroughly the syntax of the "do while" instruction in Java. We have here the keywords "do" and "while" framing the so-called loop's body : a block of instructions which we will repeat. This block is in braces. Following the keyword "while" is the continuation condition. We will repeat the instructions within the loop's body as long as the condition is evaluated as "true". In Java, similarly to the "if" instruction, the parentheses around the condition are mandatory. Also, the "do while" instruction is concluded with our famous semicolon. Similarly to the "if" instruction, the loop continuation condition can be formulated in a rather sophisticated way, for example through logical connectives. We can imagine that we wish to repeat processing as long as a variable x is equal to y plus z and that z is not equal to 0 or that y is less than 3 and so on. Thus, we see that we can formulate conditions as complex as we wish thanks to logical connectives An important remark regarding "do while" loops is that the body will always be executed at least once. Indeed, in our step by step example, we have seen that when we execute the "do while" instruction we enter the loop's body right away. Therefore, we will execute the block of instructions the first time we enter the loop. From there, it will all depend on the evaluation of the condition. The block of instructions will only be executed once if, at the first iteration, the evaluation will return false. In this case, we will indeed exit the "do while" loop and resume the processing thereafter. But, in the meantime, we will have executed the block of instructions at least once. This is a very important characteristic of the "do while" conditional loop. A last remark we can make regarding "do while" loops is that, if the condition is formulated in such a way that it will not ever become "false", the loop will be repeated indefinitely. Therefore, it is of the utmost importance to formulate the condition so that we will exit the loop at some time. The "do while" loop is a conditional loop where the condition is evaluated a posteriori. The loop's body will always be executed once before we decide if the processing will stop or be repeated. In certains situations, it is necessary to test the continuation condition a priori before executing the loop's body a single time. In such a case, we resort to another form of conditional loops, the "while" loop which we will discuss now. If we wish to write a "while" loop in Java, we use the following syntax : the keyword "while", immediately followed by the loop continuation condtion, then, in braces, the loop's body, that is the block of instructions which we wish to repeat. The operating principle is similar to the "do while" loop's : we repeat the processing as long as this condition returns the value "true". The difference between the "while" and "do while" loops is that, in "while" loops, the continuation condition is evaluted as soon we execute the "while" instruction. If this condition is evaluated as "false" from the get-go, we will never execute the block of instructions. Now, let us illustrate with two basic examples, the critical difference between "while" and "do while" loops. We have here two very similar loops. where the continuation condition depends, in both cases, on a variable i, initialized to the value 100. Let us start by examining what happens in the "do while" loop. When we execute this line, nothing prevents us from entering right away the loop's body. At this point, the message "bonjour" will be printed on the terminal. Now we execute this line, where the continuation condition will be evaluated. Since i is 100, obviously, this condition will be evaluated to "false". We will exit the loop immediately and resume with the possible instructions following the "do while" loop. In the meantime, the message "bonjour" will have been printed. Similar situation, this time with the "while" loop. When we are to execute this line, we will evaluate the continuation condition right away. As before, it will evaluated to "false". Please note that in both cases, the continuation condition has been evaluated to "false". Here, since the condition is "false" we won't even enter the loop's body and instead continue the execution after the loop's body. Therefore, in this case, the loop will not print anything. You can see that despite having two very similar loops, one will print "bonjour", while the other will not print anything. The most frequent mistakes regarding conditional loops are often related to the formulation of the continuation condition. The continuation condition is poorly formulated and we will, for example, never exit the loop or exit the loop too early, never executing the loop, which we wanted to do. However, there is a frequent syntactic mistake, which we will describe now. It is easy to fall in this trap, especially if you're unfamiliar with "while" and "do while" loops. The mistake is as follows : let us imagine that, at the end, of the "while" condition, we inadvertently add a semicolon. This mistake is made easier to commit by the fact that there is a semicolon at the end of the "do while" condition. However, this semicolon is there to conclude the whole "do while" instruction. It really does not belong here, since after the "while" condition, we expect to find a body of instructions. Here, we probably wished to put " ++i " within the body. However, what will happen here is this : when we execute the "while" instruction, everything happens as if we had a body containing but an empty instruction. So, let us imagined that we have previously initialized our variable i to a value less than 10, for example 1. Since here, the " ++1 " is outside, nothing inside the loop's body will have i evolve so that it reaches a value which will make us exit the loop. Therefore, the problem is that we will cycle indefinitely within the loop, which is an errie result to obtain, especially for beginners. Thus, be wary of these little details so that you do not fall in this trap while you are still inexperienced with programming "while" and "do while" loops. Now, you know several ways to carry out repetitive processing. the "for loop", the "while" loop and the "do while" loop. Now, you may wonder how to choose between these different forms. Actually, the choice depends on relatively simple factors. Let us detail. As we have seen in this sequence's introduction, if we do know the number of iterations, we will naturally choose a "for" loop. Let us imagine for example, that we wish to calculate the average of the grades of all this course's students. The number of students attending to this courses is known a priori and is also the the number of iterations. Therefore, we will choose a "for loop". If we do know the number of iterations, we will have to resort to a conditional loop, either "while" or "do while". Then, if the instructions are to be repeated at least once, as we have seen a few minutes ago, we will typically use a "do while" loop. In what situations does this happen ? A very typical example is the regarding interaction with the user; we need to ask a value to the user and this value is limited by some criteria. Therefore, we need to let the user input at least one value before we can test if the criteria are respected, whether or not the condition is fulfilled. In such a case, we will naturally use a "do while" loop. In all other cases, where we execute the processing only if the condition is verified, we will use a "while" loop, the condition being evaluated a priori. Let us examine now how to enrich our introductory example by adding a few more functionalities. For example, if the user inputs a number negative or null we would like to display a message signifying that it is not what the program is expecting. For example, if the user inputs minus 2, we would like to print "please type a number greater than 0". This would avoid the stubbornness we have encountered earlier, where the user would keep on entering undesired values. So, how do proceed from them ? Very clearly, this message will be printed as many times as the user types an undesired number, which could potentially be every time the user inputs a value. It is quite natural to think we should write these instructions, tasked with the printing of the message, inside the body of a loop. Therefore, we will proceed like this : we will enrich the loop's body with new instructions. So, once the user has entered the number of grades, we will test if this number of grades matches with the desired criteria. If such is not the case, we will print a message destined to the user. One of the tricks beginners encounter with "while" and "do while" loops is the formulation of an adequate continuation condition. Let us examine how to proceed thanks to a few examples. Still in our example regarding the input of a number of grades, we compelled the user to submitting a number greater than 0. Now, we also wish that this number does not exceed 10 grades. Therefore, we do not want the user to input a number greater than 10. So, how do we come up with this new condition ? To formulate this condition, the easier is probably to do so in plain words. What do we want exactly ? We want to repeat the processing asking the user to input a number of grades as long as this number is incorrect. When is this number incorrect here ? It can be in two situations. Either the user has entered a number which does not satisfy this first criteria or he has entered a number of grades which does not fulfill this second criteria. So, we find ourselves in a situation where the submitted number of grades is incorrect if the user inputs something less or equal to 0, or if they input something greater than 10. This can be translated in Java pretty easily. So, let us take back our first sentence : "if it is less or equal to 0". This is exactly what we are formulating here. OR - we can see the "OR",here - if it is greater than 10, which we are formulating here. We see here that the transition of a formulation in plain words to Java can be done in a very natural way, once we have in mind what we wish to test exactly. In a similar spirit, let us imagine that we wish to write a brief program whose purpose is to have the user guess an unknown number. To make things easier, we will assume that they have to guess the numer 5. The idea is to repeat the submission as long as the user has not guessed the correct number. So how do we formulate the condition ? As we have done in the previous example, we will start by formulating it in plain words. The loop will be repeated as long as the user has not guessed the secret number. Concretely, as long as the entered number if different from the secret number. Let us translate this formulation into Java. As long as the entered number if different from the secret number, is translated like this in Java. Yet another example where the transition from plain words into Java is very natural. Now, let us enrich this here example and imagine that we still wish to have the user guess a number but that we are only granting them a limited number of trials. If they have not guessed correctly after so many trials we stop and inform them of their failure. So, how do we modify the condtion so that the the loop stops after, for example, three unsuccessfull trials How do we formulate this condition ? The idea here, is to resort to a trial counter. We will count the number of trials; this counter will be incremented at every iteration of the loop. Now, let us formulate the condition so that depends on this counter. We will keep our method and start by formulating it in plain words : we want to repeat the processing as long as the user has not guessed the secret number and as long as he still has trials. So, let us refine the description; what does this condition exactly mean ? We iterate, repeat the processing, as long the inputted number if differrent from the secret number and as long as the trial counter is less than 3. So, now we are to translate this into Java. The transcription here is still as natural. The first condition : as long as the entered number is different from the secret number will be written like that, simply. The "and" is translated like this. And the second condition will be written like this in Java. Our user has now two possible ways to exit the loop : they can exit the loop because they have guessed the correct number, that is the inputted number has the same value as the secret number. In this case, the evaluation of this part of the condition will return "false". Since the global expression involves an "and", only one argument of the "and" needs to be bo false so that the global expression returns "false". In this case, we will exit the loop. Other possible exit condition: the user used has a number of trials greater than or equal to 3. Now, we would like to enrich our program a little bit more. We wish to inform the user of the reason why they have exited the loop. Did they exit because they have guessed the number, in which case we want to inform him of his success, or did he exit in failure ? Failure meaning they have not guessed the number before running out of trials. The trick is that it is only once we have exited the loop that we can know why we exited. Therefore, we place the instruction testing why we exited the loop at the end of the "do while" loop. So here, we will simply test if we exited the loop having guessed the secret number. In this case, we inform the user that they have won. In the other case, we will simply tell them that they have lost. Please note that we evaluate the condition "did we or not guess the correct number ?" at two different places in the program. Once in the "if", and another in the "while". It would have been smart, for good practice, to regroup these two condtions in a single variable. For example, here we could declare a boolean variable, initialized to "false" inside the loop. Then we store inside this variable, the value "entered number = secret number", Now, we can replace this condition here using our new variable. As long as the secret number has not been guessed and that the trial counter is less than 3, we will keep looping. Similarly, we could replace this condition by the evaluation "if (trouve)" (TN : trouve means, found or guessed) Therefore, we have linked two identical conditions while initially this link didn't exit : this is good practice. Now, one needs to be careful while formulating these tests. We can formulate them clumsily, causing mistakes upon execution. Here, for example, let us suppose that the user has guessed the correct number. We're testing if they have not run of trials like this. What will happen here, is that if the user has guessed the number on his third trial, what was initially a success will be interpreted as a failure. Indeed, this condition will not be verified while the secret number has actually been guessed on the third attempt. Therefore, we will unfairly inform the user that they have lost the game! This should show how important it is to think carefully while formulating the condition. Formulating the condition in an explicit way, as we did here previously, related to the secret number, will make us dodge the trap we have just analyzed in the previous example.