What are the real life examples of for, while and do while loop ?

while loop

Bijen Adhikari
4 min readMay 4, 2023

The “While” Loop is a fundamental programming construct that allows a particular set of instructions to be executed repeatedly until a specific condition is met. A practical example of this is when we need to obtain a range of data from a sensor, say between 500 and 800. In this instance, the loop continues to execute until the desired data from the sensor is retrieved. If the sensor data falls within the specified range of 500 to 800, the loop is terminated using the “break” statement. This programming concept is frequently utilized in real-world applications and is an essential technique for solving complex problem.

Example 1.

package firstprojectbijen;
import java.util.Scanner;
import java.util.Random;




public class bijen1
{
public static void main(String[] args) {
// Create a random number generator
Random random = new Random();
long sensorData;

// Keep looping until the desired sensor data is obtained
while (true) {
// Read sensor data from a source
sensorData = random.nextInt(900);
System.out.println("Sensor data: " + sensorData);

// Check if the data is within a desired range
if (sensorData >= 500 && sensorData <= 800) {
// If the data is within the range, break out of the loop
System.out.println("Desired data obtained!");
break;
}…

--

--

Bijen Adhikari

Hi, I am Bijen from Nepal I write about Electronics, Electrical, Programming, Fitness. Also, I am a certified SSI Master Trainer.