Java Array for each loop through first 5 element

Question

We have an array with 10 element and we would like to use for each loop to display the first 5 element from that array.

We also need to sum the value of first five elements.

Code structure to start with:

// Use break with a for-each style for.   
public class Main {  
  public static void main(String args[]) {  
    int sum = 0;  
    int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };  

    //Your code here
    //w w  w. j ava  2s  . co  m
 
    System.out.println("Summation of first 5 elements: " + sum);  
  }  
} 



public class Main {  
  public static void main(String args[]) {  
    int sum = 0;  
    int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };  
 
    // use for to display and sum the values  
    for(int x : nums) {  
      System.out.println("Value is: " + x);  
      sum += x;  
      if(x == 5) break; // stop the loop when 5 is obtained  
    }  
    System.out.println("Summation of first 5 elements: " + sum);  
  }  
} 

The for-each loop iterates the entire array.

We can use a break statement to terminate the looping.




PreviousNext

Related