How to Make a Loop Run Again Based on User Input in Java

Loops in Coffee

Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions repeatedly while some status evaluates to true.
Coffee provides 3 ways for executing the loops. While all the ways provide similar basic functionality, they differ in their syntax and condition checking fourth dimension.

  1. while loop: A while loop is a control menstruum argument that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be idea of equally a repeating if statement.
    Syntax :
    while (boolean condition) {    loop statements... }              

    Flowchart:
    while loop

    • While loop starts with the checking of condition. If it evaluated to true, then the loop body statements are executed otherwise first argument following the loop is executed. For this reason it is also called Entry control loop
    • Once the condition is evaluated to true, the statements in the loop trunk are executed. Unremarkably the statements contain an update value for the variable being candy for the adjacent iteration.
    • When the status becomes false, the loop terminates which marks the end of its life wheel.

    class whileLoopDemo

    {

    public static void main(Cord args[])

    {

    int x = 1 ;

    while (ten <= 4 )

    {

    Organization.out.println( "Value of x:" + ten);

    x++;

    }

    }

    }

    Output:

    Value of 10:1 Value of 10:2 Value of ten:three Value of ten:4              
  2. for loop: for loop provides a concise way of writing the loop construction. Unlike a while loop, a for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping.
    Syntax:
    for (initialization condition; testing condition;                                increase/decrement) {     argument(s) }              

    Flowchart:
    for-loop-in-java

    1. Initialization condition: Hither, we initialize the variable in use. Information technology marks the starting time of a for loop. An already declared variable can exist used or a variable tin exist declared, local to loop only.
    2. Testing Status: It is used for testing the leave condition for a loop. Information technology must render a boolean value. Information technology is likewise an Entry Control Loop as the condition is checked prior to the execution of the loop statements.
    3. Argument execution: One time the condition is evaluated to true, the statements in the loop body are executed.
    4. Increment/ Decrement: It is used for updating the variable for side by side iteration.
    5. Loop termination:When the condition becomes simulated, the loop terminates marking the cease of its life bicycle.

    form forLoopDemo

    {

    public static void main(String args[])

    {

    for ( int x = 2 ; x <= 4 ; x++)

    System.out.println( "Value of 10:" + 10);

    }

    }

    Output:

    Value of x:2 Value of x:three Value of x:4              

    Enhanced For loop

    Coffee also includes another version of for loop introduced in Java 5. Enhanced for loop provides a simpler manner to iterate through the elements of a collection or assortment. It is inflexible and should be used but when there is a need to iterate through the elements in a sequential manner without knowing the index of the currently candy element.
    Also note that the object/variable is immutable when enhanced for loop is used i.e it ensures that the values in the array can not exist modified, so it can exist said as read-merely loop where you can't update the values as opposite to other loops where values can be modified.
    We recommend using this form of the for statement instead of the general form whenever possible.(equally per Coffee md.)
    Syntax:

    for (T element:Collection obj/array) {     argument(s) }              

    Lets take an example to demonstrate how enhanced for loop can be used to simplify the work. Suppose there is an array of names and nosotros desire to print all the names in that assortment. Let's see the difference betwixt these two examples
    Enhanced for loop simplifies the work as follows-

    public class enhancedforloop

    {

    public static void main(String args[])

    {

    String array[] = { "Ron" , "Harry" , "Hermoine" };

    for (String x:assortment)

    {

    System.out.println(x);

    }

    }

    }

    Output:

    Ron Harry Hermoine              
  3. do while: exercise while loop is like to while loop with only difference that it checks for condition later executing the statements, and therefore is an example of Exit Control Loop.
    Syntax:
    do {     statements.. } while (condition);              

    Flowchart:
    do-while

    1. do while loop starts with the execution of the statement(s). There is no checking of any condition for the beginning fourth dimension.
    2. After the execution of the statements, and update of the variable value, the condition is checked for true or false value. If it is evaluated to truthful, next iteration of loop starts.
    3. When the condition becomes fake, the loop terminates which marks the stop of its life cycle.
    4. It is important to annotation that the practise-while loop will execute its statements atleast once before any condition is checked, and therefore is an example of get out command loop.

    class dowhileloopDemo

    {

    public static void main(Cord args[])

    {

    int x = 21 ;

    practice

    {

    Organization.out.println( "Value of x:" + ten);

    10++;

    }

    while (x < twenty );

    }

    }

    Output:

    Value of x: 21              

Pitfalls of Loops

  1. Space loop: One of the almost common mistakes while implementing whatever sort of looping is that that information technology may non ever exit, that is the loop runs for infinite fourth dimension. This happens when the condition fails for some reason.
    Examples:

    public grade LooppitfallsDemo

    {

    public static void main(String[] args)

    {

    for ( int i = five ; i != 0 ; i -= ii )

    {

    System.out.println(i);

    }

    int x = 5 ;

    while (x == 5 )

    {

    Arrangement.out.println( "In the loop" );

    }

    }

    }

  2. Some other pitfall is that you might exist adding something into you collection object through loop and you tin run out of memory. If you effort and execute the below plan, later some time, out of memory exception will be thrown.

    import coffee.util.ArrayList;

    public class Integer1

    {

    public static void main(Cord[] args)

    {

    ArrayList<Integer> ar = new ArrayList<>();

    for ( int i = 0 ; i < Integer.MAX_VALUE; i++)

    {

    ar.add together(i);

    }

    }

    }

    Output:

    Exception in thread "chief" coffee.lang.OutOfMemoryError: Java heap space at java.util.Arrays.copyOf(Unknown Source) at coffee.util.Arrays.copyOf(Unknown Source) at java.util.ArrayList.grow(Unknown Source) at java.util.ArrayList.ensureCapacityInternal(Unknown Source) at coffee.util.ArrayList.add together(Unknown Source) at article.Integer1.main(Integer1.java:9)              

This article is contributed by Rishabh Mahrsee. If you lot like GeeksforGeeks and would like to contribute, yous tin can besides write an article using write.geeksforgeeks.org or mail your article to review-squad@geeksforgeeks.org. Run across your article actualization on the GeeksforGeeks main page and help other Geeks.

Delight write comments if you find anything incorrect, or y'all want to share more information about the topic discussed higher up.


hurstphred1975.blogspot.com

Source: https://www.geeksforgeeks.org/loops-in-java/

0 Response to "How to Make a Loop Run Again Based on User Input in Java"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel