Header Ad

HackerRank Java 1D Array problem solution

In this HackerRank java 1D Array problem in the java programming language An array is a simple data structure used to store a collection of data in a contiguous block of memory. Each element in the collection is accessed using an index, and the elements are easy to find because they're stored sequentially in memory.

Because the collection of elements in an array is stored as a big block of data, we typically use arrays when we know exactly how many pieces of data we're going to have. 

Task

The code in your editor does the following:

  1. Reads an integer from stdin and saves it to a variable, n, denoting some number of integers.
  2. Reads n integers corresponding to a0,a1,...,an-1 from stdin and saves each integer ai to a variable, val.
  3. Attempts to print each element of an array of integers named a.

Write the following code in the unlocked portion of your editor:

  1. Create an array, a, capable of holding n integers.
  2. Modify the code in the loop so that it saves each sequential value to its corresponding location in the array. For example, the first value must be stored in a0, the second value must be stored in a1, and so on.

HackerRank Java 1D Array problem solution


HackerRank Java 1D Array problem solution.

import java.util.*;

public class Solution {

    public static void main(String[] args) {
       
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
    int[] a = new int[n];
    for(int i = 0; i < n; i++){
        a[i]=scan.nextInt();
    }

        scan.close();

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



Second solution

import java.util.*;

public class Solution {

    public static void main(String[] args) {
       
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
      int[] a = new int[n];
        for(int i = 0 ; i < n; i++){
          int val = scan.nextInt();
            a[i] = val;
      }
        scan.close();

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

Post a Comment

0 Comments