Array Initialization and Traversal
This program demonstrates initialization and traversal of a single dimensional array.
Problem Statement
Write a Java program to initialize an integer array with 5 elements and print them sequentially.
Source Code
| 1 | public class ArrayInitializationTraversal { |
| 2 | public static void main(String[] args) { |
| 3 | int[] arr = {10, 20, 30, 40, 50}; |
| 4 | for(int i=0; i<arr.length; i++) { |
| 5 | System.out.println("Element at index " + i + ": " + arr[i]); |
| 6 | } |
| 7 | } |
| 8 | } |
Program Output
Element at index 0: 10 Element at index 1: 20 Element at index 2: 30 Element at index 3: 40 Element at index 4: 50
Explanation
The array arr is initialized with 5 integers, and arr.length provides the size used by the for loop to iterate from index 0 to 4, accessing each element with arr[i], demonstrating basic array initialization and traversal and how arrays store multiple values in contiguous memory.