#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2013
    Posts
    62
    Rep Power
    2

    Nested for loops


    how can you tell if this nested loop if looping left to right or top to bottom?

    Code:
    for(int y = 0; y < a.length; y++){
       for(int x = 0; x < a[y].length; x++){
            System.out.println(a[x][y]);
        }
    }
    A:
    0 1 2 3
    4 5 6 7
    8 9 10 11

    i trying to loop though 2d array from left to right ex:
    ------->
    ------->
    ------->


    and i guess if i switch the x and y inside print system than it will loop though like this:
    | | |
    | | |
    | | |
    V V V
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Location
    /dev/null
    Posts
    162
    Rep Power
    18
    If the variable in outer loop (i.e. y) is the first index of array and variable in inner loop (i.e. x) is the second index of array, then the traversal appears to be from left to right.
    Code:
    public class TestClass {
      public static void main(String[] args) {
        int[][] a = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
    
        for (int y = 0; y < a.length; y++) {
          for (int x = 0; x < a[y].length; x++) {
            System.out.print(a[y][x]);
          }
          System.out.println();
        }
      }
    }
    If the variable in inner loop (i.e. x) is the first index of array and variable in outer loop (i.e. y) is the second index of array, then the traversal appears to be from top to bottom.
    Code:
    public class TestClass {
      public static void main(String[] args) {
        int[][] a = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
    
        for (int y = 0; y < a.length; y++) {
          for (int x = 0; x < a[y].length; x++) {
            System.out.print(a[x][y]);
          }
          System.out.println();
        }
      }
    }
    By the way, you could have tried a sample program and deduced the analogy yourself.

IMN logo majestic logo threadwatch logo seochat tools logo