Save as "Sdis.java"
public static void main(String[] args)
{
int n, i;
Scanner in = new Scanner(System.in);
int[] arr = new int[20];
System.out.println("Enter the number of elements in the array:");
n = in.nextInt();
System.out.println("Enter array elements:");
for(i=1;i<=n;i++)
arr[i] = in.nextInt();
if(n == 0 || n == 1)
System.out.println("Array empty or lacks the minimum no of elements required to find the distance!!");
else
{
int spos = Sdisfind(arr,n);
System.out.println("The smallest distance exists between " + arr[spos] + " at pos " + spos + " and " + arr[spos+1] + " at pos " + (spos+1));
}
}
public static int Sdisfind(int[] array, int arrlength )
{
int sdis, tdis, pos1,i;
pos1 = 1;
sdis = Math.abs(array[1] - array[2]);
for (i = 1; i < arrlength; i++)
{
tdis = Math.abs(array[i] - array[i+1]);
if (tdis < sdis)
{
sdis = tdis;
pos1 = i;
}
}
return pos1;
}
}
public static void main(String[] args)
{
int n, i;
Scanner in = new Scanner(System.in);
int[] arr = new int[20];
System.out.println("Enter the number of elements in the array:");
n = in.nextInt();
System.out.println("Enter array elements:");
for(i=1;i<=n;i++)
arr[i] = in.nextInt();
if(n == 0 || n == 1)
System.out.println("Array empty or lacks the minimum no of elements required to find the distance!!");
else
{
int spos = Sdisfind(arr,n);
System.out.println("The smallest distance exists between " + arr[spos] + " at pos " + spos + " and " + arr[spos+1] + " at pos " + (spos+1));
}
}
public static int Sdisfind(int[] array, int arrlength )
{
int sdis, tdis, pos1,i;
pos1 = 1;
sdis = Math.abs(array[1] - array[2]);
for (i = 1; i < arrlength; i++)
{
tdis = Math.abs(array[i] - array[i+1]);
if (tdis < sdis)
{
sdis = tdis;
pos1 = i;
}
}
return pos1;
}
}
0 comments :
Post a Comment