Write a java program to find average of prime locations.

Write a program to read an integer array and find the average of the numbers located on the Prime location(indexes).

  • Round the average to two decimal places.
  • Assume that the array starts with index 0.
  • The return type (double) should be the average

Input and Output Format:

Input consists of n+1 integers. The first integer corresponds to n, the number of elements in the array. The next ‘n’ integers correspond to the elements in the array.

  • Output consists of a single Double value.
  • Refer to sample output for formatting specifications.
  • Assume that the maximum number of elements in the array is 20.

Find the average of prime locations in Java.

import java.text.DecimalFormat;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    int[] a = new int[20];
    int n = sc.nextInt();
    for (int i = 0; i < n; i++) {
      a[i] = sc.nextInt();
    }

    System.out.print(display(n, a));
  }

  public static double display(int n, int[] a) {
    int count = 0, sum = 0, n1 = 0, d = 0;
    int count1 = 0;
    double avg = 0;

    for (int i = 2; i < n; i++) {
      count = 0;
      for (int j = 1; j <= i; j++) {
        if (i % j == 0) {
          count++;
        }
      }
      if (count == 2) {
        sum = sum + a[i];
        count1++;
      }
    }
    avg = (double) (sum) / count1;
    DecimalFormat df = new DecimalFormat("#.00");
    double ddd = Double.parseDouble(df.format(avg));
    return ddd;
  }
}

Sample Input 1:

8

4

1

7

6

5

8

6

9

Sample Output 1:

7.5

You May Also Like These Posts:

Leave a Reply

Your email address will not be published.

10 − 7 =