Array 01a
Array 01a
dataType[] arrayName;
dataType - it can be primitive data
types like int , char , double , byte , etc.
or Java objects
arrayName - it is an identifier
For example,
double[] data;
Here, data is an array that can hold values
of type double .
But, how many elements can array this
hold?
Good question! To define the number of
elements that an array can hold, we have to
allocate memory for the array in Java. For
example,
// declare an array
double[] data;
// allocate memory
data = new double[10];
Here, the array can store 10 elements. We
can also say that the size or length of the
array is 10.
In Java, we can declare and allocate the
memory of an array in one single statement.
For example,
// declare an array
int[] age = new int[5];
// initialize array
age[0] = 12;
age[1] = 4;
age[2] = 5;
..
Note:
Array indices always start from 0. That is,
the first element of an array is at index 0.
If the size of an array is n , then the last
element of the array will
be at index n-1 .
1. import java.util.Scanner;
2. public class
Search_Element
3. {
4. public static void
main(String[] args)
5. {
6. int n, x, flag =
0, i = 0;
7. Scanner s = new
Scanner(System.in);
8.
System.out.print("Enter no.
of elements you want in
array:");
9. n = s.nextInt();
10. int a[] = new
int[n];
11.
System.out.println("Enter
all the elements:");
12. for(i = 0; i < n;
i++)
13. {
14. a[i] =
s.nextInt();
15. }
16.
System.out.print("Enter the
element you want to
find:");
17. x = s.nextInt();
18. for(i = 0; i < n;
i++)
19. {
20. if(a[i] == x)
21. {
22. flag = 1;
23. break;
24. }
25. else
26. {
27. flag = 0;
28. }
29. }
30. if(flag == 1)
31. {
32.
System.out.println("Element
found at position:"+(i +
1));
33. }
34. else
35. {
36.
System.out.println("Element
not found");
37. }
38. }
39. }