In: Computer Science
Write Java program Lab43.java which declares and initializes numeric array of 5 elements (int num[5]) and produces as output the sum of integers in an array, the largest and the smallest element in an array. Your program should contain the following methods:
Code
public class Lab43 {
public static void main(String[] args) {
int []a={10,50,80,40,20};
System.out.print("Our array is : ");
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
int s=sum(a);
int largest=findLargest(a);
int smallest=findSmallest(a);
System.out.println("\n\nSum of the array: "+s);
System.out.println("\nLargest from the array: "+largest);
System.out.println("\nSmallest from the array: "+smallest);
}
private static int sum(int[] a) {
int sum=0;
for(int i=0;i<a.length;i++)
sum+=a[i];
return sum;
}
private static int findLargest(int[] a) {
int max=a[0];
for(int i=1;i<a.length;i++)
if(max<a[i])
max=a[i];
return max;
}
private static int findSmallest(int[] a) {
int min=a[0];
for(int i=1;i<a.length;i++)
if(min>a[i])
min=a[i];
return min;
}
}
output
If you have any query regarding the code please ask me in the comment i am here for help you. Please do not direct thumbs down just ask if you have any query. And if you like my work then please appreciates with up vote. Thank You.