In Java, there are three main types of loops you can use to repeat code:

  1. For Loop
    This loop is used when you know the exact number of times you want to execute the code. The syntax is:

    for (initialization; condition; update) { // code to be executed }

    Example:

    for (int i = 0; i < 5; i++) { System.out.println("Count: " + i); }

    This will print the numbers 0 to 4.

  2. While Loop
    This loop is used when you want to repeat code as long as a condition is true. It’s ideal for situations where you don’t know the exact number of iterations in advance.

    while (condition) { // code to be executed }

    Example:


    int i = 0; while (i < 5) { System.out.println("Count: " + i); i++; }
  3. Do-While Loop
    Similar to the while loop, but this loop guarantees that the code block will execute at least once, because the condition is checked after the code executes.


    do { // code to be executed } while (condition);

    Example:


    int i = 0; do { System.out.println("Count: " + i); i++; } while (i < 5);

Each type of loop has its own use case, depending on when you need to check the condition and how many times you expect to iterate.

Comments

Post a Comment

Popular posts from this blog