Array programs in Java

Vinnu Mukhi
2 min readMay 27, 2021

Check Array is Sorted or not!

public class Arrays {
public static void main(String[] args) {
int [] array= {1,2,3,4,5,6,7};
boolean isSorted=true; //by default isSorted is True
for(int i=0;i< array.length-1;i++){
if(array[i]>array[i+1]){
isSorted=false;
break;
}
}
if(isSorted){
System.out.println("The Array is sorted");
}
else {
System.out.println("The array is not sorted");
}
}
}
Output: The Array is sorted

Calculate the Sum and Find the Average value of it

public class Arrays {
public static void main(String[] args) {
float [] marks= {10.5f ,30.5f ,40.5f ,50.7f};
float sum=0;
for (float element:marks){
sum= sum+element;
}
System.out.println("The Value of Sum is = "+ sum/marks.length);
}
}
Output: The Value of Sum is = 33.05

Add the 2x3 Size matrix and print

public class Arrays {
public static void main(String[] args) {
int[][] mat1 = {{2, 3, 4},
{2, 3, 4}};
int[][] mat2 = {{4, 3, 2},
{2, 3, 4}};
int[][] result = {{0, 0, 0}, {0, 0, 0}};
for (int i = 0; i < mat1.length; i++) { //row numbers of time
for (int j = 0; j < mat1[i].length; j++) { //column numbers of time
System.out.format("Setting value for i=%d and j=%d\n", i, j);
result[i][j] = mat1[i][j] + mat2[i][j];
}
}
for (int i = 0; i < mat1.length; i++) { //row numbers
for (int j = 0; j < mat1[i].length; j++) { //column numbers
System.out.print(result[i][j]+ " ");
result[i][j] = mat1[i][j] + mat2[i][j];

}
System.out.println(""); //For line Change
}
}
}
Output: Setting value for i=0 and j=0
Setting value for i=0 and j=1
Setting value for i=0 and j=2
Setting value for i=1 and j=0
Setting value for i=1 and j=1
Setting value for i=1 and j=2
6 6 6
4 6 8

--

--

Vinnu Mukhi
0 Followers

I'm a Computer Science Student from Indore (India) and I'm Sharing all my learnings here.