Java 1D Array Solution


Problem Overview

Original Problem: Java 1D Array | HackerRank

Difficulty: Easy

Category: Arrays, Data Structures

Description: We are given a number, followed by multiple integers. Our task is to store these integers in a one-dimensional array and ensure that each value is stored at its correct index.

Understanding the Problem

The problem here is a simple task that requires us to iteratively read input and store numbers in a one-dimensional array by correctly accessing the array indices.

Input:

Multiple lines of input, where:

  • The first line contains an integer that represents the number of elements in the array

  • The following lines each contain an integer to be stored in the array

Output:

The output is handled for you by the template code. It prints each element of the array on a new line.

Initial Reasoning

The original problem gives us template code to read the first line of input and handles the output. From here, we will need to create an array based on the first line of input, iteratively read the remaining integers, and store them in an array.

Pseudocode

// Main function:
Read the array size 
Create an array 
For each remaining input
	Read the integer and store it in the array
For each item in the array
	Print the array item on a separate line

Solution Code

// Note this is one of many possible solutions
import java.util.*;

public class Solution {

    public static void main(String[] args) {
	   
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();    // The size of the array
        int[] a = new int[n];      // Declare and initialize an array of size n

        for (int i = 0; i < n; i++) {
            a[i] = scan.nextInt(); // Read and assign each value to array at index i
        }

        scan.close();

        // Prints each sequential element in array a
        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }
    }
}