Java Array multidimensional Arrays for each loop iterate

Introduction

We can use the for-each loop on multidimensional arrays.

Java multidimensional arrays is arrays of arrays.

A two-dimensional Java array is an array of one-dimensional arrays.

// Use for-each style for on a two-dimensional array.  
public class Main {  
  public static void main(String args[]) {  
    int sum = 0;  
    int nums[][] = new int[3][5];  
  
    // give nums some values  
    for(int i = 0; i < 3; i++)   
      for(int j=0; j < 5; j++)  
        nums[i][j] = (i+1)*(j+1);  //from   w ww . j a  v a 2s  .  co  m
  
    // use for-each for to display and sum the values  
    for(int[] x : nums) {  
      for(int y : x) { 
        System.out.println("Value is: " + y);  
        sum += y;  
      } 
    }  
    System.out.println("Summation: " + sum);  
  }  
}



PreviousNext

Related