
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Elements Greater Than Previous and Next Element in Array in C++
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].
Program to illustrate the working of our solution,
Example
#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