Wednesday, 15 July 2015

Java Programs Made Easy

Q)...A integer array is given as input. find the difference between each element.
 Return the index of the largest element which has the largest difference gap.
input: {2,3,4,2,3}
logic: 2-3=1,3-4=1,4-2=2,2-3=1
2 is the max diff between 4 and 2,return the index of 4(2)
output:2

  1. package Set1;
  2. public class ClassSet3 {
  3.  public static int getDiffArray(int[] n1){
  4.   int n2,n3=0,n4=0,i;
  5.   for(i=0;i<n1.length-1;i++){
  6.    n2=Math.abs(n1[i]-n1[i+1]);
  7.    if(n2>n3){
  8.     n3=n2;
  9.     n4=i+1; }}
  10.   return n4;
  11.  }
  12.  public static void main(String[] args) {
  13.   int[] n1={2,9,4,7,6};
  14.   System.out.println(getDiffArray(n1));
  15.  }
  16. }