Rose Marie
ArrayJava
1 Answer(s)      6 years and a month ago
Posted in : Java Beginners

a java program that accepts 10 integers. the program returns the sum, average, the smallest and the largest element from the array list

Ads

View Answers

November 23, 2010 at 12:32 PM


Hi Friend,

Try the following codes:

1)Using Array:

import java.util.*;
class  ArrayExample{
    public static int getMaxValue(int[] arr){
  int maxValue = arr[0];
  for(int i=1;i < arr.length;i++){
    if(arr[i] > maxValue){
      maxValue = arr[i];
    }
  }
  return maxValue;
}

public static int getMinValue(int[] arr){
  int minValue = arr[0];
  for(int i=1;i<arr.length;i++){
    if(arr[i] < minValue){
      minValue = arr[i];
    }
  }
  return minValue;
}
    public static void main(String[] args) 
    {
        int sum=0;

        Scanner input=new Scanner(System.in);
        System.out.println("Enter Array Elements: ");
        int array[]=new int[10];
        for(int i=0;i<array.length;i++){
            array[i]=input.nextInt();
        sum+=array[i];

        }
        System.out.println("Sum Of Array Elements is: "+sum);
        System.out.println("Average of Array Elements is: "+sum/array.length);
        System.out.println("Smallest No: "+getMinValue(array));
        System.out.println("Largest No: "+getMaxValue(array));
    }
}

2)Using ArrayList:

import java.util.*;
class  ArrayListExample{
    public static void main(String[] args){
        int sum=0;
        Scanner input=new Scanner(System.in);
        System.out.println("Enter Array Elements: ");
        ArrayList list=new ArrayList();
        for(int i=0;i<10;i++){
        int num=input.nextInt();
        list.add(num);
        }
        for(int i=0;i<list.size();i++){
            sum+=Integer.parseInt(list.get(i).toString());
        }
        System.out.println("Sum Of ArrayList Elements is: "+sum);
        System.out.println("Average of ArrayList Elements is: "+sum/list.size());
        Collections.sort(list);
        System.out.println("Smallest No: "+list.get(0));
        System.out.println("Largest No: "+list.get(list.size()-1));
    }
}

Thanks










Related Tutorials/Questions & Answers: