Print Same Statement Over Again Without Loop
While loop in Java: conditional loop that repeats the code multiple times
Keywords: while loop, conditional loop, iterations sets
This article will look at the while loop in Java which is a provisional loop that repeats a lawmaking sequence until a sure condition is met. We will start by looking at how the while loop works then focus on solving some examples together.
While loop in Coffee
The while loop in Java is a and so-called condition loop. This ways repeating a code sequence, over and over once more, until a condition is met. In other words, you lot utilize the while loop when you desire to repeat an operation equally long as a condition is met. Instead of having to rewrite your code several times, we can instead repeat a code block several times. In general, information technology tin can exist said that a while loop in Coffee is a repetition of ane or more sequences that occurs equally long every bit one or more atmospheric condition are met.
The while loop evaluates expression, which must return a boolean value. If the expression evaluates to true, the while loop executes thestatement(s) in the code block. The while loop continues testing the expression and executing its block until the expression evaluates to simulated.
Oracle
How while loop in Java works?
The while loop is used to iterate a sequence of operations several times. In other words, y'all repeat parts of your program several times, thus enabling general and dynamic applications because code is reused any number of times. If the number of iterations not is fixed, it'south recommended to use a while loop.
The flow chart in Figure ane below shows the functions of a while loop
Figure i: While loop in Java
Let'southward break information technology down
- The code sequence begins at Commencement and so checks if the loop conditions are met.
- If the condition is met, true, the plan performs the operation.
- When these operations are completed, the lawmaking volition return to the while condition.
- The loop so repeats this process until the condition is false, and so the program continues.
In short, the while loop in java:
- Is a loop that repeats a sequence of operations an capricious number of times.
- Repeats the operations equally long as a condition is true.
- Enables full general and dynamic applications because code tin can be reused.
- All-time suited when the number of iterations of the loop is not fixed.
How to create a while loop in Coffee
While loop in Coffee:
- Yous create the while loop with the reserved word while, followed by a status in parentheses ( )
- Within the curly brackets, { }, you specify all operations that you want to execute equally long as the condition is true.
- The loop repeats itself until the status is no longer met, that is, false.
Syntax: Declare while loop in Java
If we use the elements in the list higher up and insert in the code editor:
while (condition) { // While loop code block } Examples: While loop in Coffee
Let's encounter a few examples of how to use a while loop in Java.
Example 1: Create a while loop in Coffee
The following examples evidence how to use the while loop to perform one or more operations equally long a the status is truthful.
public class Example{ public static void main(String[] args) { int i = 0; // As long as the "i" is less than five, the loop is executed while(i < 5){ System.out.println("How-do-you-do, World!"); // Increment the variable each footstep, i = i + one i++; } } } Furthermore, in this example, we print Hullo, World! every bit long equally the condition is true, in other words, as long as the variable i is less than five. The program will thus impress the text line Hello, World! five times and so finish the while loop:
Hello, Globe! Hello, World! Hello, World! Hello, World! Hello, World!
Note, what would have happened if i++ had not been in the loop? Thats right, since the condition will always exist true (zero is e'er smaller than five), the while loop will never stop. The program will and then impress Hello, Globe! forever. This is a so-called infinity loop that we mentioned in the article introduction to loops.
If you lot would like to exam the lawmaking in the case in an online compile, click the push below.
Case 2: While loop to compare two numbers
In this case we are going to:
- Accept two numbers, one large that we proper noun large, and one smaller, that nosotros call small-scale. Both numbers are randomly selected to illustrate the example
- Use a while loop to print the value of both numbers every bit long every bit the large number is larger than the small number.
- For each iteration in the while loop, we will divide the large number past 2, and also multiply the smaller number past 2.
public static void primary(String[] args) { int large = 2345; int small = 3; while (large > small){ System.out.println("Large = " + large + " and " + "Small = " + small); big = large / 2; small-scale = small * two; } } The reply in this example volition be
Big = 2345 and Pocket-size = 2 Large = 1172 and Minor = 4 Large = 586 and Small = 8 Large = 293 and Modest = 16 Large = 146 and Minor = 32 Large = 73 and Minor = 64
Instance 3: While loop using a random number
Let'south accept a look at a third and last instance. In this case, we volition utilize the random grade to generate a random number. If you do not think how to utilize the random class to generate random numbers in Java, you can read more about it here.
What we want our program to do is:
- Generate a random number between 0 – 15.
- While that number is not equal to 12, the currently generated random number should be printed, as well as how far the current number is from 12 in absolute numbers.
- Finally, once we have reached the number 12, the programme should cease past printing out how many iterations it took to attain the target value of 12.
// Import the Scanner class import coffee.util.Random; public class exempel { public static void principal(Cord[] args) { // Creates a scanner object Random rand = new Random(); // Creates a random integer int randomNum =rand.nextInt(xv); // Variable for number of iterations int count = 0; // As long equally the random number is not equal to 12 while(randomNum != 12){ System.out.println("Number is: " + randomNum + ", that is: " + Math.abs(12 - randomNum) + " from target value"); // Update the random number randomNum = rand.nextInt(fifteen); // Increment the counter variable by one count ++; } // Print number of iterations Organisation.out.println("Target value reached in: " + count + " iterations"); } } Furthermore, in this case, it will non exist easy to print out what the answer will be since nosotros become unlike answers every time. Merely information technology might look something like:
Number is: 5, that is: 7 from target value Number is: 4, that is: 8 from target value Number is: 4, that is: viii from target value Number is: 7, that is: 5 from target value Number is: viii, that is: iv from target value Target value reached in: 6 iterations
Why use a while loop in Java?
The while loop in Coffee used to iterate over a lawmaking block equally long every bit the condition is truthful. We unremarkably use the while loop when we practise not know in accelerate how many times should exist repeated. Furthermore, a while loop volition keep until a predetermined scenario occurs. Information technology can happen immediately, or it tin crave a hundred iterations. Then the number of loops is governed by a effect, not a number. For example, you tin can proceed the loop until the user of the programme presses the Z fundamental, and the loop volition run until that happens.
Mutual errors when using the while loop in Java
- First of all, you finish up in an infinity loop, due to several reasons, but could, for case, be that you forget to update the variables that are in the loop. Note that your compiler volition end the loop, but it will as well cause your program to crash/shut down, and you volition receive an error message.
- You lot forget to declare a variable used in terms of the while loop. Call up that the beginning time the status is checked is before yous start running the loop torso.
- Incorrect with one in the number of iterations, ordinarily due to a mismatch between the state of the while loop and the initialization of the variables used in the status. A good thought for longer loops and more all-encompassing programs is to test the loop on a smaller scale earlier.
That was merely a couple of common mistakes, there are of course more mistakes you can brand
Help us improve CodeKnowledge
Please leave feedback and help us continue to make our site better.
Summary: While loop in Java
A while loop in Coffee is a so-chosen condition loop. This means repeating a code sequence, over and over over again, until a condition is met. Instead of having to rewrite your code several times, nosotros can instead repeat a code block several times. If the number of iterations not is fixed, it's recommended to use a while loop.
Syntax: While loop
while (condition) { // While loop code block } FAQ: While loop in Java
What is the condition of the while loop?
The expression that the loop will evaluate. As long as that expression is fulfilled, the loop will be executed. For example, it could exist that a variable should exist greater or less than a given value.
Can you use the while loop even if you know the number of iterations?
Yep, of grade. It is possible to set a condition that the while loop must go through the code block a given number of times. Only for that purpose, it is normally easier to utilize the for loop that we volition see in the adjacent article.
Can I utilise a while loop within another while loop?
Yes, information technology works fine. But recall to keep in mind that loops can "get stuck" in an infinity loop and so that you pay attention and then that your programme can movement on from the loops.
Source: https://code-knowledge.com/java-while-loop/
0 Response to "Print Same Statement Over Again Without Loop"
Post a Comment