Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

public class ArrayIndex { public static void main(String[] args) { final int Arr

ID: 645153 • Letter: P

Question

public class ArrayIndex

{
public static void main(String[] args)
{
final int Array_Length = 6;
int[] array = new int[Array_Length];
  
for(int counter = 0; counter < array.length; counter++)
array[counter] = 2 * counter;
  
System.out.printf("%s%8s%n", "Index", "Amount");
  
for (int counter = 0; counter < array.length; counter++)
System.out.printf("%5d%8d%n", counter, array[counter]);
}
}

So the above program will display (minus the dots):

run:
Index Amount
0................0
1.................2
2................4
3................6
4...............8
5...............10
BUILD SUCCESSFUL (total time: 9 seconds)

What is the next step of this code that will display Index 2 Amount 4? This is Java from the chapter on Arrays and ArrayLists.

Explanation / Answer

/**
* Arrays are accessed using index locations.
* So to access element at location 2, use index=2
* to get the value stored at arrray
* */
//ArrayIndex.java
public class ArrayIndex

{
   public static void main(String[] args)
   {
       final int Array_Length = 6;
       int[] array = new int[Array_Length];
      
       for(int counter = 0; counter < array.length; counter++)
       array[counter] = 2 * counter;
      
       System.out.printf("%s%8s%n", "Index", "Amount");
      
       for (int counter = 0; counter < array.length; counter++)
       System.out.printf("%5d%8d%n", counter, array[counter]);
      
      
      
       //In arrays ,elements can be accessed using its index positions
       //To print the index 2 and Amount 2
       //create a index variable and set to 2
       int index=2;
       System.out.println();
       System.out.println("At index "+index);
      
       System.out.printf("%5d%8d%n", index, array[index]);
      
      
   }
}

----------------------------------------------------------------------------------------------------------------------------------------

Sample output:

Index Amount
    0       0
    1       2
    2       4
    3       6
    4       8
    5      10

At index 2
    2       4

Hope this helps you