# Elements greater than the previous and next element in an Array in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array arr[] of n positive integers. Our task is to create a program to find the elements greater than the previous and next element in an Array.

Code Description: We need to find the elements of the array that satisfy the condition, the element is greater that the element at index 1 less than it and also is greater than the element at index 1 greater than it.

## Let’s take an example to understand the problem,

Input: arr[] = {3, 2, 5, 7, 3, 4, 5}

Output: 7

Explanation −

Element with index one less than the current element, 5.
Element with index one more than the current element, 3.

The current element is greater than both.

## Solution Approach −

A simple solution to the problem is by checking the condition for each element of the array and then print the element that satisfies the condition.

For this we need to follow these steps−

Step 1: Loop through the elements of the array from index 1 to n-2.

Step 1.1: for each element, arr[i]. We will check if arr[i] > arr[i-1]  and arr[i] > arr[i+1].

Step 1.2: If it is true, print arr[i].

## Example

Live Demo

#include <iostream>
using namespace std;

void findElemenetsInArray(int arr[], int n) {

for (int i = 1; i < n-1; i++)
if ( (arr[i] > arr[i+1] && arr[i] > arr[i-1]) ) {
cout<<arr[i]<<"\t";
}
}

int main()
{
int n = 8;
int arr[n] = { 5, 4, 7, 1, 17, 8, 3 };
cout<<"The elements that satisfy the given condition are ";
findElemenetsInArray(arr, n);
return 0;
}

## Output −

The elements that satisfy the given condition are 7 17

Published on 22-Jan-2021 12:38:53