array in java
array in java
Scanner;
2. public class array
3. {
4. public int max(int [] array)
5. {
6. int max = 0;
7.
8. for(int i=0; i<array.length; i++ )
9. {
10. if(array[i]>max)
11. {
12. max = array[i];
13. }
14. }
15. return max;
16. }
17.
18. public int min(int [] array)
19. {
20. int min = array[0];
21.
22. for(int i = 0; i<array.length; i++ )
23. {
24. if(array[i]<min)
25. {
26. min = array[i];
27. }
28. }
29. return min;
30. }
31.
32. public static void main(String args[])
33. {
34. Scanner sc = new Scanner(System.in);
35. System.out.println("Enter the array range");
36. int size = sc.nextInt();
37. int[] arr = new int[size];
38. System.out.println("Enter the elements of the array ::");
39.
40. for(int i=0; i<size; i++)
41. {
42. arr[i] = sc.nextInt();
43. }
44. array m = new array();
45. System.out.println("Maximum value in the array is::"+m.max(arr));
46. System.out.println("Minimum value in the array is::"+m.min(arr));
47. }
48. }
Output:
Example 2:
Computing an array of Random Numbers
Random numbers are those numbers whose occurrence is random and cannot be
predicted reasonably.
Below is the example code through which we can understand the passing of an array
to a function and generate random numbers:
Note: In the case of random numbers, always the result will vary as the numbers are
generated randomly.
Example 3:
Sorting numbers of an array
Below is an example code where we pass an array to a function and sort the elements
of the given array:
1. class array
2. {
3. public static void main(String[] args)
4. {
5. int[] n={12,24,2,89,34,45};
6. System.out.println("Before sorting");
7. display(n);
8. sort(n);
9. System.out.println("\n After Sorting :");
10. display(n);
11. }
12. static void display(int n[])
13. {
14. for(int i=0; i<n.length;i++)
15. System.out.print(n[i] + " ");
16. }
17. static void sort(int n[])
18. {
19. int i, j, temp;
20. for(i=0; i<n.length-i;i++)
21. {
22. for(j=0; j<n.length-i-1;j++)
23. {
24. if(n[j]>n[j+1])
25. {
26. temp = n[j];
27. n[j] = n[j+1];
28. n[j+1] = temp;
29. }
30. }
31. }
32. }
33. }