Join Regular Classroom : Visit ClassroomTech

Wipro NLTH Coding Solve | Sum of Adjacent Distances | Codewindow.in

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 Total distance function only which receive the first parameter as the number of items in the array, and second parameter as the array itself. You are not requested to take input from the console.

Constraints
NA

Example

Finding the total distance between adjacent items of a list of 5 numbers

Input:
5
10 11 7 12 14

Output:
12

Explanation
The first parameters (5) is the size of the array next is an array of integers the total of distance is 12 as per the calculation below.
10-11=1
11-7=4
7-12=5
12-14=2
Total distance-1+4+5+2=12

#include 
int main()
{
    int n;
    scanf("%d", &n);
    int i,a[n];
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    int sum=0,t;
    for(i=0;i<n-1;i++)
    {
        t=a[i]-a[i+1];
        if(t<0)
        t=-t;
        sum=sum+t;
    }
    printf("%d",sum);
}

Also Checkout

Recent Posts
Categories
Pages