# Consecutive difference of elements in Array

In this post we will be discussing about
how to calculate the difference between two consecutive number in an array. Also,
the required logic is discussed and the coding part is written in C++.

**Problem Description **

You are given with a circular array. Your
task is calculate the difference between two consecutive number. And if
difference is greater than ‘k’, print 1 else print 0

**Input Description:**

You are given two numbers ‘n’, ’m’. Next line contains n space separated
integers.**Output Description:**

Print 1 if the difference is greater than ‘m’.**Sample Input :**

5 1550 65 85 98 35

**Sample Output :**

0 1 0 1 0**Logic to follow to come-up with the
solution :**

1. Declare the required sets of variables
to use in the code.

2. Input the user input size of the
array and its elements.

3.Now iterate from initialization as
0 till the second last element.

4. And inside it finds the absolute
difference of two consecutive numbers, also if the difference is greater than
the inputted value then prints 1 or in other case print 0.

**
(Absolute convert the -ve computed
value into +ve. Ex. abs (-15) ****à**** 15)**

5. Now iterate from second last
element till the last element, this is done to compute the difference of last
and first element of the array.

6. Similarly, inside it find the
absolute difference of two consecutive numbers, also if the difference is
greater than the inputted value then prints 1 or in other case print 0.

7. At last we get the required set of the 1’s and 0’s by computing the absolute difference.

**Let’s write the required code for the
problem :**

**Code :**

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | #include <iostream> using namespace std; int main() { int n,k; cin>>n>>k; int a[n]; for(int i=0;i<n;i++) { cin>>a[i]; } for(int i=0;i<n-1;i++) { if(abs(a[i]-a[i+1])>k) { cout<<"1 "; } if(abs(a[i]-a[i+1])<=k) { cout<<"0 "; } } for(int i=n-1;i<n;i++) { if(abs(a[n-1]-a[0])>k) { cout<<"1"; } if(abs(a[n-1]-a[0])<=k) { cout<<"0"; } } return 0; } |

**Sample Test Cases have been passed
successfully**

You can run same set of code at this
portal, click here to
go to the online portal and just give required set of inputs and click on
Execute to run the program.

If you liked this post, then share this
with your friends and if anything is confusing or incorrect then let me know in
the comment section.

Thanks from my side, this is Mayank, keep learning and exploring !!