Years ago when I wanted to use use a while loop I never thought about its categories, I just used because sometimes it easier to manage larges iterations, but it good to know more about it, and in which situation use it.
While Loops are loops that can execute a block of code as long as the specified condition is meet.
There are two types of repetitions control categories for the while loops; count-controlled repetitions and sentinel-controlled repetitions
Count-Controlled repetitions is the one that executes and after do it an amount of times it terminates and example of this is the method below:
public static void counterControlled(int input) {
/*
* The CounterControlled is programmed to end after it is executed a fixed
* amount of times for example Challenge: Print all the even numbers from 1-10
* Count-controlled while loop Must have
*/
// stating point
int num = 1;
// ending condition
while (num <= input) {
if (num % 2 == 0) {
System.out.print("[" +num + "]" + " ");
// a process to go from
}
// begining to ending
num = num + 1;
}
System.out.println("-------------------");
}
Sentinel-Controlled repetitions terminates its execution after a designate value is called in the code below we could see an example of this:
Scanner myObjectInput = new Scanner(System.in);
System.out.println("Enter stop to finish");
String stopingLoop = "";
while ((!(stopingLoop = myObjectInput.nextLine()).equalsIgnoreCase("stop"))) {
System.out.println("Say Whaaaat ?");
}
System.out.println("You " + stopingLoop + "ped the loop");
myObjectInput.close();
In the code we could see that if we want to get out the while loop we just have to type the word “stop” because it is the designated value to terminate it.
When we are dealing with While loops it is very important to set a closing statement to terminate it because if not we are going to be falling in a infinite loop and we don’t want that , this is called (OBOE) which stands for “off-by-one-error”, we could appreciate an example of this in the code below:
int count = 0;
while(count != 20){
count = count + 3;
System.out.println(count);
}
The code above won’t stop running because it will never reach it closing statement to terminate it, that’s what we should make sure we set a limit to our loop , for example to fix the code above we use the expression <= 20 so whenever it reach to 20 it will stop.
An useful tool when it comes to math operations it is use these



