Total Distance between adjacent elements of an array. A c++ program to find Total Distance between adjacent elements of an array

 

A C++ Program to Find Total Distance between Adjacent Elements of an Array

        This is most common question in placement tests and technical interviews. In this program the size of the array an array will be provided by user and based on these inputs we need to find the total distance between the adjacent elements of the given array.

The solution is provided in below parts.
  1.  Logic of Code
  2.  C++ code 



Find the total distance between adjacent elements of an array.

Input : 

5
10 11 7 12 14

Output :

12

Explanation :

10 - 11 =  1
11 - 7 =  4
7 - 12 =  5
12 - 14 =  2

Total Distance  =  1 + 4 + 5 + 2  =  12

Hence the Total Distance is 12.


LOGIC :

  •  Input Size of Array
  •  Input Array 
  •  In a loop calculate the difference between adjacent elements
  •  Calculate sum of all differences
  •  Print the Sum

CODE :

#include <iostream>
 using namespace std;

int totaldistance(int n, int arr[]){ int sum=0; for(int i=0;i<n-1;i++){ int x=abs(arr[i]-arr[i+1]); sum=sum+x; } return sum; } int main() { int n; cin>>n; int arr[n]; for(int i=0;i<n;i++){ cin>>arr[i]; } cout<<totaldistance(n,arr)<<endl; }



!! SUBSCRIBE FOR MORE CODES & VIDEOS !!



Post a Comment

0 Comments