An array is collection of values of same datatype.Its length is decided when it is created.It has index by which its element are accessed.
Index of array is always from 0 to n-1 ( for n size of array).
import java.util.Scanner;
public class arrayexp {
public static void main(String[] args) {
int i;
Scanner sc = new Scanner(System.in);
System.out.println("enter how much element u want in array ");
i=sc.nextInt();
int Arry[] = new int[i];
System.out.println("enter element s");
for(int a=0;a Arry[a]=sc.nextInt();
}
System.out.println("Elements in array are ");
for(int a=0;a System.out.print(" "+Arry[a]);
}
}
}
Output
enter how much element u want in array
4
enter element s
2
4
6
8
Elements in array are
2 4 6 8
Index of array is always from 0 to n-1 ( for n size of array).
- How to declare array?
- How to allocate memory to array?
array-name = new datatype[size];
Example( array_name= new int[10];) or (array_name=new float[15]).
size is number of elements you can store array.
- How you can initialize array?
array_name[1]=value1;
Example
array_name[0]=1;
array_name[2]=4;
Above example state that '1' value is stored at position 0 and '4' at position 2.
- How to access element of array at some position ?
System.out.println("Elements at position 1"+array_name[1]);
- How to do initialize and declare array in same step?
Program Example in Eclipse
public class arrayexp {
public static void main(String[] args) {
int i;
Scanner sc = new Scanner(System.in);
System.out.println("enter how much element u want in array ");
i=sc.nextInt();
int Arry[] = new int[i];
System.out.println("enter element s");
for(int a=0;a Arry[a]=sc.nextInt();
}
System.out.println("Elements in array are ");
for(int a=0;a System.out.print(" "+Arry[a]);
}
}
}
Output
enter how much element u want in array
4
enter element s
2
4
6
8
Elements in array are
2 4 6 8
No comments:
Post a Comment