Calculating values to be placed into elements of an array. - Java Language Basics

Java examples for Language Basics:Array

Description

Calculating values to be placed into elements of an array.

Demo Code

public class Main 
{
   public static void main(String[] args)
   {//from  w  w  w.j  a  v a  2  s .c o m
      final int ARRAY_LENGTH = 10; // constant
      int[] array = new int[ARRAY_LENGTH]; // create array

      // calculate value for each array element
      for (int counter = 0; counter < array.length; counter++)
         array[counter] = 2 + 2 * counter;

      System.out.printf("%s%8s%n", "Index", "Value"); // column headings
   
      // output each array element's value 
      for (int counter = 0; counter < array.length; counter++)
         System.out.printf("%5d%8d%n", counter, array[counter]);
   } 
}

Result


Related Tutorials