How to Take Array Input in Java - The Coding Shala
In this post, we will learn how to take an array input in Java.
How to Take Array Input in Java
Write a Java Program to take array input from the user. In this program, we are going to take only an integer array as input.
We are going to use the Scanner class to take integer inputs. The below are steps to take array input:
- Take the size of the array as input.
- Create the array of the above size.
- Using for loop take integer elements from the user as input.
- Print the array.
Java Program:
import java.util.Scanner; /** * https://www.thecodingshala.com/ */ public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the size of array"); int size = sc.nextInt(); // create an array of given size int[] arr = new int[size]; // take integer inputs using for loop System.out.println("Enter " + size + " elements"); for (int i=0; i < size; i++) { arr[i] = sc.nextInt(); } // print array System.out.println("The Array is: "); for (int i=0; i < size; i++) { System.out.print(arr[i] + " "); } } }
Output:
Enter the size of array 5 Enter 5 elements 1 2 3 4 5 The Array is: 1 2 3 4 5
- Java Program to Print the Sum of all Elements of the Array
- Java Program to Find the Largest Element in the Array
- Java Program to Reverse an Array
- Java Program to Concat Two Arrays
- Java Program to Reverse a String
Comments
Post a Comment