How to take input numbers into an Array in Java - The Coding Shala
Home >> Java Programs >> How to take input numbers into an Array
Other Posts You May Like
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
- Java Program to Add Two Numbers
- Java Program to Find Sum of Digits of a Number
- Java Program to Check if given Year is leap or not
- Java Program to Swap Two Numbers
- Java Program to Multiply Two Numbers
Comments
Post a Comment