Wednesday, 15 July 2015

Java Programs Made Easy


Q)... Get a integer array as input. Find the average of the elements which are in the position of prime index
input:{1,2,3,4,5,6,7,8,9,10}
logic:3+4+6+8(the indeces are prime numbers)
output:21



  1. package Set1;
  2. import java.util.*;
  3. public class ClassSet20 {
  4.  public static int sumOfPrimeIndices(int[] a,int n){
  5.   int n1=0;
  6.   for(int i=2;i<n;i++){
  7.    int k=0;
  8.    for(int j=2;j<i;j++)
  9.     if(i%j==0)
  10.      k++;
  11.    if(k==0)
  12.     n1+=a[i]; }
  13.   return n1;
  14.  }
  15.  public static void main(String[] args) {
  16.   Scanner s=new Scanner(System.in);
  17.   System.out.println("enter the array limit:");
  18.   int n=s.nextInt();
  19.   System.out.println("enter the array elements:");
  20.   int[] a=new int[n];
  21.   for(int i=0;i<n;i++)
  22.    a[i]=s.nextInt();
  23.   System.out.println(sumOfPrimeIndices(a,n));
  24.  }
  25. }