A
A
Alexander2020-11-13 21:47:04
C++ / C#
Alexander, 2020-11-13 21:47:04

How many array elements are greater than their neighbors (previous and next elements)?

I wrote a program that prints out how many elements of an array are greater than their neighbors.

#include <iostream>
using namespace std;

int main()
{
  double ARR[25];
  int count = 0;
  
  cout << "Enter the elements of the array:" << endl;

  for (int i = 0; i < 25; i++)
  {
    cout << i + 1 << ") ";
    cin >> ARR[i];
  }

  cout << "\nArray: { ";
  for (int i = 0; i < 25; i++)
  {
    cout << ARR[i] << " ";
  }
  cout << "}";

  for (int i = 0; i < 25; i++)
  {
    if (ARR[i] > ARR[i + 1] && ARR[i] > ARR[i - 1])
      count++;
  }
  cout << "\n\nResult: " << count;

  cin.clear();
  cin.ignore(numeric_limits<streamsize>::max(), '\n');
  cin.get();

  return 0;
}

Everything works fine, but there is a little nuance: the first and last elements have only one neighboring element.
How can I make it so that the first and last elements are not taken into account?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2020-11-13
@AlexB_49

To skip the first and last elements, simply change the boundaries of the loop: If you want to count these elements if they are greater than their only neighbor, then use lazy evaluation of logical formulas (when calculating A || B, if A == true, then B is not evaluated at all will):
for (int i = 1; i < 24; i++)

for (int i = 0; i < 25; i++)
  {
    if ((i +1 == n || ARR[i] > ARR[i + 1]) && 
         (i == 0 || ARR[i] > ARR[i - 1]))
      count++;
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question