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.
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;
}
0 Comments