Instagram
youtube
Facebook
Twitter

Print each sequential element on a new line program with Java HackerRank Solutions

Task

  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.

Input Format

The first line contains a single integer, n, denoting the size of the array.
Each line i of the n subsequent lines contains a single integer denoting the value of element ai.

Output Format

You are not responsible for printing any output to stdout. Locked code in the editor loops through array a and prints each sequential element on a new line.

Sample Input

5
10
20
30
40
50

Sample Output

10
20
30
40
50

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 < a.length; i++) {
            a[i] = scan.nextInt();
        }
        scan.close();

        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }
    }
}

Steps involved in this solution:

1. Import the java.util package, which includes the Scanner class for taking user input.

2. Define a class named Solution, which will contain the main method.

3. Define the main method, the entry point of the program.

4. Create a Scanner object named scan to read input from the user.

5. Read an integer n, representing the size of the array.

6. Create an array a of size n. Use a loop to read n integers from the user and store them in the array.

7. Close the Scanner to release resources.

8. Use a loop to iterate through the array and print each element on a new line.

9. Close the class definition.