Answer to Question #276254 in C++ for zain

Question #276254

Programming Problem I ( class, queue, Linked list )

Given a collection of integers, how do you check whether each successive pair of numbers in the collection is consecutive or not. The pairs can be increasing or decreasing.

 For example, if the collection of elements are [4, 5, -2, -3, 11, 10, 6, 5] then the output should be true because each of the pairs (4, 5), (-2, -3), (11, 10), and (5, 6) consists of consecutive numbers. But if collection is [4,6,9,8] it should return false.


1
Expert's answer
2021-12-07T09:56:59-0500
#include <iostream>
#include <cmath>

using namespace std;

int main( void ) 
{
 int n;
 cin >> n;

 int arr[n];
 for (int i = 0; i < n; i++)
  cin >> arr[i];

 sort( arr, arr + n );

 bool flag = true;
 for (int i = 0; i < 2 * (n / 2); i++) {
  if (abs(arr[i] - arr[i-1]) > 1) flag = false;
 }
 cout << flag << endl;
 return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment