How to take input numbers into an Array in Java - The Coding Shala

Home >> Java Programs >> How to take input numbers into an Array

 In this post, we will learn how to take input numbers into an Array using the scanner in Java.

Java Program to take input numbers into an Array

Write a Java Program that takes numbers as input and inserts those elements into an Array.

Example 1:
Input: number of elements = 5
         elements are = 1 2 3 4 5
Output: arr = [1, 2,3,4,5]

Java Program: 

// Java program to take input numbers into array

import java.util.Scanner;

public class Main {
	
	public static void main(String[] args) { 
		Scanner sc = new Scanner(System.in);
		
		System.out.println("Enter the size of array");
		int num = sc.nextInt();
		
		// declare array
		int[] arr = new int[num];
		
		System.out.println("Enter " + num + " numbers");
		for(int i = 0; i < num; i++) {
			arr[i] = sc.nextInt();
		}
		
		
		// print array
		System.out.print("Array elements are: ");
		for(int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + " ");
		}
		
		sc.close();
	}
}

Output: 

Enter the size of array
5
Enter 5 numbers
1
2
3
5
2
Array elements are: 1 2 3 5 2 


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Java Program to Convert Binary to Decimal - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Introduction to Kotlin Programming Language for Backend Development - The Coding Shala

Java Program to Reverse a String using Stack - The Coding Shala