Answer the question
In order to leave comments, you need to log in
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;
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question