Array

Lab Objective

The goal of this lab is to provide you with hands-on experience working with Java arrays and iterating over an Array using loops.

Instructions

Example 1: Access Array Elements

Create a class named arraydemoOne and write the below code.

public class arraydemoOne {
  public static void main(String[] args) {

   // create an array
   int[] age = {12, 4, 5, 2, 5};
   // access each array elements
   System.out.println("Accessing Elements of an Array:");
   System.out.println("First Element: " + age[0]);
   System.out.println("Second Element: " + age[1]);
   System.out.println("Third Element: " + age[2]);
   System.out.println("Fourth Element: " + age[3]);
   System.out.println("Fifth Element: " + age[4]);
  }
}

Output:

In the above example, notice that we are using the index number to access each element of the array.

We can use loops to access all the array elements at once.

Example 2: Using for Loop

Create a class named arraydemoTwo and write the code below in it

Output:

In the above example, we are using the for Loop in Java to iterate through each element of the array. Notice the expression inside the loop, age.length.

Example 3: Iterating Over an Array using EnhancedForLoop

Create a class named EnhancedForLoop and write the code below.

Output:

Example 4: Compute the Sum and Average of Array Elements

Create a class named arraydemothree and write the code below.

Output:

In the above example, we have created an array of named numbers. We have used them for...each loop to access each array element. Inside the loop, we calculate the sum of each element. Notice the line: int arrayLength = numbers.length; Here, we are using the length attribute of the array to calculate the size of the array. We then calculate the average using: average = ((double)sum / (double)arrayLength); As you can see, we are converting the int value into a double. This is called "type casting” in Java.

Example 5: Mean and Standard Deviation

Find the mean and standard deviation of the numbers kept in an array.

Create a class named MeanSDArray and write the code below.

Output:

Example 6: Insert an Element at the end of an Array in Java

Create a class named insertElements and write the code below.

The snapshot given below shows the sample run of the above program, with user input 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 as ten elements and 500 as the new element to insert at the end of array:

Last updated