Implement a java program to find the smallest distance between two neighbouring numbers in an array.

Answers

Answer 1
Answer:

Answer:

Here is the JAVA program to find smallest distance between 2 neighboring numbers in an array.

import java.lang.Math; // for importing Math class functions

import java.util.Scanner; // for importing Scanner class

public class CalSmallestDistance // class to calculate smallest distance

{public static void main(String[] args) {     // to enter java program

    Scanner s = new Scanner(System.in);  //creating scanner object

    int size; // size of the array

  System.out.print("Enter size of the array:"); //prompts to enter array size

       size = s.nextInt(); // reads input

       int arr[] = new int[size];  // array named arr[]

      //line below prompts to enter elements in the array             System.out.println("Enter numbers in the array:");

       for(int j = 0; j < size; j++)        //loops through the array

           {arr[j] = s.nextInt(); }     //reads the input elements

      int smallest_distance = Math.abs(arr[0]-arr[1]);  

       int position= 0; //index of the array

       for(int i=1; i<arr.length-1; i++){

           int distance= Math.abs(arr[i]-arr[i+1]);

           if(distance< smallest_distance){

           smallest_distance= distance;

           position = i;            }        }

  System.out.println("Smallest distance is :"+smallest_distance);

System.out.println("The numbers are  :"+arr[position]+ " and " +arr[position+1]);      } }

Explanation:

I have stated the minor explanation of some basic lines of code as comments in the code given above.

Now i will give the detailed explanation about the working of the main part of the code.

Lets start from here

      int smallest_distance = Math.abs(arr[0]-arr[1]);  

In this statement the array element at 0 index (1st position) and the array element at 1 index (2nd position) of the array are subtracted.

Then i used the math.abs() method here  which gives absolute value

Lets say the distance between 3 and 5 is -2 as 3-5 equals to -2. But the math.abs() method will return 2 instead of -2.

Now the subtraction of two array elements and absolute value (if subtraction result is negative) will be assigned to variable smallest_distance.

       for(int i=1; i<arr.length-1; i++)

This is for loop. Variable i is positioned to the 1 index of the array (arr) (it is pointing to the second element of the array). It will move through the array until the end of the array is reached i.e. the loop will continue till value of i remains less than the length of the array.

Now at the start of the loop body the following statement is encountered

           int distance= Math.abs(arr[i]-arr[i+1]);

This subtracts the array element at i th position and array element at i th +1 position (means one position ahead of array element at i th position). In simple words two neighboring numbers in an array are being subtracted and Math.abs() method is used to give absolute value. The result of this operation is assigned to distance variable.

           if(distance< smallest_distance)

This if statement checks if the value in distance variable is smallest than the value of smallest_distance variable which was previously calculated before calculating the value for distance variable.

If this condition is true then the following statements are executed:

             smallest_distance= distance;

if distance value is less than value in smallest_distance, then the value of distance is assigned to smallest_distance.

this means the smallest_distance will keep on storing the smallest distance between two neighboring numbers.

Next the value of variable i that is pointing to the 1st index of the array is now assigned to the position variable.

                                         position = i;

It will keep assigning the value of i to position variable so at the end of the program we can get the positions of the two neighboring numbers that have the smallest distance between them.

Then the value of i is incremented and moves one place ahead in the array.

Then the 2nd iteration takes place and again checks if i pointer variable has reached the end of the array. If not the loop body will continue to execute in which the distance between the two neighboring numbers is calculated and shortest distance is stored in smallest_distance.

When i reaches the end of the array the loop will break and the smallest distance between two neighboring numbers in the array have been stored in the smallest_distance variable.

Finally the statement System.out.println("Smallest distance is :"+smallest_distance); displays the shortest distance and the statement System.out.println("The numbers are  :"+arr[position]+ " and " +arr[position+1]); displays the array index positions at which the two neighboring numbers have the smallest distance.


Related Questions

What is not an operating system
Caleb Co. owns a machine that had cost $42,400 with accumulated depreciation of $18,400. Caleb exchanges the machine for a newer model that has a market value of $52,000. 1. Record the exchange assuming Caleb paid $30,000 cash and the exchange has commercial substance. 2. Record the exchange assuming Caleb paid $22,000 cash and the exchange has commercial substance.
A ________ topology uses more than one type of topology when building a network. crossover multiple-use fusion hybrid
Juan Garcia is the network administrator for a small company that also maintains its own web server. He has taken the following precautions: All the computers are patched, have antivirus software, and have unneeded services shut down. The network has a firewall with proxy server and IDS. The organization has a policy requiring passwords of ten characters in length, and must be changed every 90 days. Has Juan done enough to secure the network
Consider the following two code segments, which are both intended to determine the longest of the three strings "pea", "pear", and "pearl" that occur in String str. For example, if str has the value "the pear in the bowl", the code segments should both print "pear" and if str has the value "the pea and the pearl", the code segments should both print "pearl". Assume that str contains at least one instance of "pea".I.if (str.indexOf("pea") >= 0){System.out.println("pea");}else if (str.indexOf("pear") >= 0){System.out.println("pear");}else if (str.indexOf("pearl") >= 0){System.out.println("pearl");}II.if (str.indexOf("pearl") >= 0){System.out.println("pearl");}else if (str.indexOf("pear") >= 0){System.out.println("pear");}else if (str.indexOf("pea") >= 0){System.out.println("pea");}Which of the following best describes the output produced by code segment I and code segment II?Both code segment I and code segment II produce correct output for all values of str.Neither code segment I nor code segment II produce correct output for all values of str.Code segment II produces correct output for all values of str, but code segment I produces correct output only for values of str that contain "pear" but not "pearl".Code segment II produces correct output for all values of str, but code segment I produces correct output only for values of str that contain "pearl".Code segment II produces correct output for all values of str, but code segment I produces correct output only for values of str that contain "pea" but not "pear".

You need to design online to form in which users have to type their name and password to log into an application. The password can be acombination of numbers and letters. Which data type is most suitable for a password field?
The
data type is most suitable to define a password field.

Answers

Answer:

Data Type String

Explanation:

Hope it helps. pls mark as brainliest.

one of the 4 vs of big data that refers to uncertainty due to data inconsistency and incompleteness, ambiguities, latency, deception, and model approximations is . select one: veracity volume validity variety

Answers

one of the 4 vs of big data that refers to uncertainty due to data inconsistency and incompleteness, ambiguities, latency, deception, and model approximations is veracity.

What is veracity?

Conformity with truth or fact : accuracy. : devotion to the truth : truthfulness. 3. /vəˈraes.ə.ti/ the quality of being true, honest, or accurate: Doubts were cast on the veracity of her alibi. Synonyms.  Veracity is the quality of being true or the habit of telling the truth. He was shocked to find his veracity questioned. Veracity refers to the quality of the data that is being analyzed. High veracity data has many records that are valuable to analyze and that contribute in a meaningful way to the overall results. Low veracity data, on the other hand, contains a high percentage of meaningless data. This type of source is the starting point for any historian-researcher. Some written sources are forgeries.

To know more about veracity visit:

brainly.com/question/21093435

#SPJ4

What is the use of form in HTML​

Answers

Answer:

to make the internet faster

Explanation:

becuase it will have a faster act on the computer so the computer could process the information for it later to be used

Write an if statement that assigns 100 to x when y is equal to 0. 32. Write an if/else statement that assigns 0 to x when y is equal to 10. Otherwise it should assign 1 to x. 33. Using the following chart, write an if/else if statement that assigns .10, .15, or .20 to commission, depending on the value in sales. Sales Commission Rate Up to $10,000 10% $10,000 to $15,000 15% Over $15,000 20%

Answers

Answer:

1.  

if(y==0.3){ x = 100;}

2.

if(y == 10){

x = 0; }

else {

x = 1; }

3.

if(sales< 10000){

commission = 0.10;

}

else if(sales>= 10000 && sales <= 15000 ){

commission = 0.15;

}

else{

commission = 0.20;

}

Explanation:

The statements written in brackets represent the conditions while the statements in {...} represent the operation that would be executed depending on the outcome of the if statement.

For 1: if(y==0.3){ x = 100;}

If y is 0.3, 100 would be assigned to x

For 2:

if(y == 10){ x = 0; }

If y is 10, 0 would be assigned to x

else { x = 1; }

If otherwise, 1 would be assigned to x

For 3:

if(sales< 10000){commission = 0.10;}

Is sales is less than 10000, commission would be 0.10

else if(sales>= 10000 && sales <= 15000 ){commission = 0.15;}

If sales is within range of 10000-15000, commission would be 0.15

else{commission = 0.20;}

If otherwise, commission would be 0.20

Define a function below called average_strings. The function takes one argument: a list of strings. Complete the function so that it returns the average length of the strings in the list. An empty list should have an average of zero. Hint: don't forget that in order to get a string's length, you need the len function.

Answers

The required code written in python 3 which returns the average of the strings in a list goes thus :

def average_strings(string_list):

#initializeafunctionnamedaverage_stringwhichtakesinalistofstringasparameter

total_length = 0

#initializetotallengthofstringto0

if len(string_list)==0:

#checksofthe stringisempty

return 0

#ifstringisemptyreturn0

for word in string_list :

total_length += len(word)

#addthelength ofeachstringtothetotallengthofthe string.

return total_length / len(string_list)

#returntheaveragevalue

A sample run of the function is given here and the output attached.

string_list = ['dog', 'cat', 'mouse']

print(average_strings(string_list))

Learn more :brainly.com/question/15352352

Answer:

def average_strings(lst):

   total = 0

   if len(lst) == 0:

       return 0

   for s in lst:

       total += len(s)

   return total / len(lst)

Explanation:

Create a function called average_strings that take one parameter, lst

Initialize a total to hold the length of the strings in lst

If the length of lst is 0, return 0

Otherwise create a for loop that iterates through the lst. Calculate the length of each string in lst and add it to total

When the loop is done, return the average, total length of the strings divided by length of the lst

When emergency changes have to be made to systems, the system software may have to be modified before changes to the requirements have been approved. Suggest a model of a pro- cess for making these modifications that will ensure that the requirements document and the system implementation do not become inconsistent.

Answers

Answer:

The Agile model

Explanation:

We can point out that this is all about the software development lifecycle model. In the software developmental lifecycle, the agile model is the most suited model that can be used to bring changes as per the requirement.

It is the model that provides huge flexibility as the changes can be made to the software even if the application is running. Moreover, this model follows documentation regarding the process of bringing the changes to the software. And even the new changes should pass the quality assurance test in order to go to the production phase.

What this does is that it actually ensures that your application is fit and is consistent to handle and perform operations.