Computer Science, asked by divyasenthil63, 6 months ago

Question
Write a program to calculate and return the sum of distances between the
adjacent numbers in an array of positive integers
Note:
You are expected to write code in the find TotalDistance function only which will
receive the first parameter as the number of items in the array and second
parameter as the array itself. You are not required to take input from the console
Example
Finding the total distance between adjacent items of a list of 5 numbers
Input
input1: 5
input2: 10 11 7 12 14
Output
12
program​

Answers

Answered by rakeshchatty
44

Public int findTotalDistance(int input1, int[] input2){

int sum=0;

int currentVal=0;

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

currentVal = input2[i] - input2[i+1];

sum = sum + Math.abs(currentVal);

}

return sum;

Attachments:
Answered by Agastya0606
0

The program for the given problem is:-

def findTotalSum(n,numbers,pos):

  total = 0

  for i in range(pos-1,n-1):

      total+= abs(numbers[i]-numbers[i+1])

  return total

n = int(input())

numbers = list(map(int, input().split()))

pos = int(input())

print(findTotalSum(n,numbers,pos))

  • A function with the name findTotalSum is defined at first.
  • Then a for loop is used.
  • An integer variable is input by the user.
  • After the implementation of the required condition the value is printed.

#SPJ3

Similar questions