adsense


Monday, 26 October 2015

JAVA EXAMPLES USE FOR AND FOREACH LOOPS PAGE 85

COMPUTER LANGUAGES HTML,C,C++.JAVA,.NET AND MULTIMEDIA basics and programs click home button



JAVA EXAMPLES USE FOR AND FOREACH LOOPS


Java Examples - Use for & foreach loops



Problem Description:
How to use for and foreach loops to display elements of an array.
Solution:
This example displays an integer array using for loop & foreach loops.
public class Main {
   public static void main(String[] args) {
      int[] intary = { 1,2,3,4};
      forDisplay(intary);
      foreachDisplay(intary);
   }
   public static void forDisplay(int[] a){  
      System.out.println("Display an array using for loop");
      for (int i = 0; i < a.length; i++) {
         System.out.print(a[i] + " ");
      }
      System.out.println();
   }
   public static void foreachDisplay(int[] data){
      System.out.println("Display an array using for 
      each loop");
      for (int a  : data) {
         System.out.print(a+ " ");
      }
   }
}
Result:
The above code sample will produce the following result.
Display an array using for loop
1 2 3 4 
Display an array using for each loop
1 2 3 4 


No comments: