What is array: An array is a collection of elements of same data type stored in a single variable. It allows to store multiple values (like numbers or strings) in one variable instead of declaring separate variables for each value.
Properties of array:
a. The size of array is fixed.
b. All the elements in array must be of same data type.
c. Array is an index-based subscript which starts with the value 0.
d. Every array has a built-in variable .length that gives the size of the array.
In Java, the minimum length of an array is 0, and the maximum length depends on the maximum value of the int type, since array indices are represented by integers.
Ex: To print a set of numbers given in an array
class Array{
public static void main(String [] args){
int[] marks = {87,90,97,84,95};
System.out.println(marks[0]);
System.out.println(marks[1]);
System.out.println(marks[2]);
System.out.println(marks[3]);
System.out.println(marks[4]);
}
}
Output:
87
90
97
84
95
To find the maximum value
class Bubblesort{
public static void main(String[] args){
int [] marks = {97,98,99,86,83};
int max = marks[0];
int second_max = 0;
for (int i=1; i<marks.length; i++)
if (marks[i]>max){
second_max = max;
max = marks[i];
}
else if (marks[i]>second_max)
{
second_max = marks[i];
}
System.out.println(max);
System.out.println(second_max);
}
}
Output:
Maximum mark: 99
Second maximum mark: 98
To find minimum and second minimum:
class Bubblesort {
public static void main(String[] args) {
int[] marks = {97, 93, 91, 86, 83};
int min = marks[0];
int second_min = Integer.MAX_VALUE;
for (int i = 1; i < marks.length; i++) {
if (marks[i] < min) {
second_min = min;
min = marks[i];
} else if (marks[i] < second_min) {
second_min = marks[i];
}
}
System.out.println(min);
System.out.println(second_min);
}
}
Output:
83
86
Top comments (0)