1 and 2 Dimensional Array in Java
1 and 2 Dimensional Array in Java
1 and 2 Dimensional Array in Java
Using Scanner
1. Read the array length as sc.nextInt() and store it in the
variable len and declare an array int[len].
As you can see in the example given above, firstly, you need to 2) To store elements in to the array for i=0 to i<length of an
declare the elements that you want to be in the specified array. array read the element using sc.nextInt() and store the element
Secondly, the location of each element needs to particularized as at the index a[i].
well, since that is where the elements will be stored respectively. 3) Display the elements of an array for loop iterates from i=0 to
Thirdly, you need to declare the array accordingly. i<length of an array print the array element a[i].
1 import java.util.*;
As it is visible, the three elements that have been listed 2 class OnedimensionalScanner
simultaneously are as follows: 3 {
4 public static void main(String args[])
10 5 {
20 6 int len;
30 7 Scanner sc=new Scanner(System.in);
8 System.out.println("Enter Array length : ");
Hence, the result is printed as 10 20 30 respectively in single 9 len=sc.nextInt();
lines, since it is a one-dimensional array. 10 int a[]=new int[len];//declaration
11 System.out.print("Enter " + len + " Element to Store in Array :\n");
12 for(int i=0; i<len; i++)
Thus, the methods used to do so in Java are as follows: 13 {
14 a[i] = sc.nextInt();
15 } 1. We declared one-dimensional string array with the
16 System.out.print("Elements in Array are :\n");
17 for(int i=0; i<len; i++)
elements strings.
18 { 2) To print strings from the string array. for i=0 to i<length of
19 System.out.print(a[i] + " ");
20 }
the string print string which is at the index str[i].
21 } One Dimensional Array Java Program Using String
22 }
1 class OneDimensionString
Output: 2 {
1 Enter Array length : 3 public static void main(String[] args)
2 4 4 {
3 Enter 4 Element to Store in Array : 5 //declare and initialize one dimension array
4 1 6 String[] str = new String[]{"one", "two", "three", "four"};
5 2 7 System.out.println("These are elements of one Dimensional array.");
6 3 8 for (int i = 0; i < str.length; i++)
7 4 9 {
8 Elements in Array are : 10 System.err.println(str[i] + " ");
9 1 2 3 4 11 }
12 }
13 }
Output:
1 These are elements of one Dimensional array.
2 one
Using For Loop – One Dimensional Array 3 two
4 three
1 class OnedimensionalLoop 5 four
2 {
3 public static void main(String args[])
4 {
5 int a[]={10,20,30,40,50};//declaration and initialization
6 System.out.println("One dimensional array elements are :\n");
7 for(int i=0;i<a.length;i++)
8 {
9 System.out.println("a["+i+"]:"+a[i]);
10 }
11 }
12 }
Output:
One dimensional array elements are :
1
a[0]:10
2
a[1]:20
3
a[2]:30
4
a[3]:40
5
a[4]:50
6
7