This program is designed to create an array and then print all of its elements.
Now, let’s understand the concept of arrays.
Arrays are unique variables that can store multiple values under a single name. These values are stored in a consecutive manner in memory. Each element within the array can be accessed using its corresponding index.
In this case, the elements of the array can be represented by the numbers 1, 2, 3, 4, and 5. Each element within the array can be accessed using its corresponding index, which in this case would be 0, 1, 2, 3, and 4.
Algorithm for a Java Code to print the elements of an array
STEP 1: Start
STEP 2: Initialize the array arr[] with values {1, 2, 3, 4, 5}.
STEP 3: Print “Elements of the given array:”.
STEP 4: Repeat STEP 5 for each index i from 0 to the length of arr[].
STEP 5: Print the value at arr[i].
STEP 6: End.
Java Code to print the elements of an array
public class PrintArray { public static void main(String[] args) { //Initialize array int [] arr = new int [] {1, 2, 3, 4, 5}; System.out.println("Elements of given array: "); //Loop through the array by incrementing value of i for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } }
Output:
Elements of given array: 1 2 3 4 5
In conclusion, the Java program provided aims to print all the elements of an array. It follows a step-by-step approach to accomplish this task. The program initializes an array with given values and then utilizes a loop to iterate through the array and print each element. By implementing this program, one can effectively display all the elements present in the array. Follow tutorials.freshersnow.com to learn more.