ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Loops
    Java 2022. 2. 7. 21:11

    자바의 반복문에 대해 정리하였습니다.

     

     


    < Introduction to Loops >

    To repeat the same block of code until some condition is met.

    We employ loops to easily scale programs - saving time and minimizing mistakes.

     

    • Writing the same code over and over is time-consuming.
    • Having less code means having less to debug.

     

     


    While loop >

    < Syntax >
    while (condition) {
      // code block
    }​
    If the condition evaluates to true, the code block will run.
    If the condition evaluates to false, the code block will stop.

     

    Example)

    int number = 1;
    
    while (number <=6) {
      System.out.println(number);
      number += 1;
    }
    
    // 1 2 3 4 5 6

     

     


    Incrementing While Loops >

    To avoid Infinity Loops using counter.

     

    • counter (a.k.a iterator) is a variable used in the conditional logic of the loop and (usually) incremented in value during each iteration through the code.

     

    Example)

    int wishes = 0;
     
    while (wishes < 3) {
      System.out.println("Wish granted.");
      wishes++;
    }
    
    // Wish granted.
    // Wish granted.
    // Wish granted.

    : Counter is wishes variable

     

     


    For Loops >

    < Syntax >
    for (int control-variable = 0; control-variable < 5; control-variable++) {
    	// code block
    }
    A for loop is made up of the following three parts, each separated by a semicolon ;
    1. The initialization of the loop control variable.
      => int control-variable = 0
    2. A boolean expression.
      => control-variable < 5;
    3. An increment or decrement statement.(On each iteration after initialization)
      => control-variable++
    : The for loop will continue to execute until boolean expression is false

     

    Example)

    int[] secretCode = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    for (int i = 0; i < secretCode.length; i++) {
      // Increase value of element value by 1
      secretCode[i] += 1;
    }
    // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

     

     


    < break and continue >

    To exit a loop before it finishes or want to skip one of the iterations, we can use the break and 
    continue keywords.

     

    1. The break keyword is used to exit, or break, a loop.

    : Once break is executed, the loop will stop iterating.

    for (int i = 0; i < 10; i++) {
      System.out.println(i);
      if (i == 4) {
        break;
      }
    }
    // 1
    // 2
    // 3
    // 4

     

    2. The continue keyword is used inside of a loop if we want to skip an iteration.

    : Once continue is executed, the current loop iteration will immediately end, and the next iteration will begin.

    int[] numbers = {1, 2, 3, 4, 5};
    for (int i = 0; i < numbers.length; i++) {
      if (numbers[i] % 2 == 0) {
        continue;
      }
      System.out.println(numbers[i]);
    }
    
    // 1
    // 3
    // 5

     

     

    +. Loops can exist all throughout our code - including inside a method

    If the return keyword was executed inside a loop contained in a method, then the loop iteration would be stopped and the method/constructor would be exited.

    public static boolean checkForJacket(String[] lst) {
      for (int i = 0; i < lst.length; i++) {
        System.out.println(lst[i]);
        if (lst[i] == "jacket") {
          return true;
        }
      }
      return false;
    } 
     
    public static void main(String[] args) {
      String[] suitcase = {"shirt", "jacket", "pants", "socks"};   
      System.out.println(checkForJacket(suitcase));
    }
    
    // shirt
    // jacket
    // true

     

     


    < For-Each Loops >

    To directly loop through each item in a list of items (like an array or ArrayList) and perform some action with each item.

    For loop's Short Version!


     

    < Syntax >
    for (DataType element : list) {
      // code block
    }
    1. DataType : element's data type.
    2. element : list's element's name.(anything you want)
    3. list : list(like array or ArrayList) to iterate.

     

    Example)

    // For
    for (int inventoryItem = 0; inventoryItem < inventoryItems.length; inventoryItem++) {
      System.out.println(inventoryItems[inventoryItem]);
    }
    
    // For-Each
    for (String inventoryItem : inventoryItems) {
      System.out.println(inventoryItem);
    }

     

     


    Removing Elements During Loop >

    When an element is removed from an ArrayList, all the items that appear after the removed element will have their index value shift by negative one — it’s like all elements shifted to the left. We’ll have to be very careful with how we use our counter variable to avoid skipping elements.

     

    < 1. Removing An Element Using while >

    When using a while loop, should not increment the counter variable.

    We don’t need to increase the counter because all of the other elements have now shifted to the left.

    int i = 0;
    
    while (i < lst.size()) {
      // if value is odd, remove value
      if (lst.get(i) % 2 != 0){
        lst.remove(i);
      } else {
        // if value is even, increment counter
        i++;
      }
    }

     

    < 2. Removing An Element Using for >

    When using a for loop, we can’t avoid increasing control variable.

    So we should decrease the control variable whenever we remove an item.

    for (int i = 0; i < lst.size(); i++) {
      if (lst.get(i) == "value to remove"){
        // remove value from ArrayList
        lst.remove(lst.get(i));
        // Decrease loop control variable by 1
        i--;    
      }
    }

     

     

     

     

     

    'Java' 카테고리의 다른 글

    Access, Encapsulation, and Scope  (0) 2022.02.08
    String Methods  (0) 2022.02.07
    ArrayLists  (0) 2022.02.06
    Array  (0) 2022.02.05
    Conditional Operators  (0) 2022.02.05

    댓글

Designed by Tistory.