w3resource

C++ Exercises: Find the next greater element of every element of a given array of integers

C++ Array: Exercise-8 with Solution

Write a C++ program to find the next greater element of every element of a given array of integers. Ignore those elements which have no greater element.

Pictorial Presentation:

C++ Exercises: Find the next greater element of every element of a given array of integers

Sample Solution:

C++ Code :

#include<iostream>
using namespace std;

void next_greater(int nums[], int n)
{
    stack<int> data_stack;
 
    data_stack.push(nums[0]);
 
   for (int i=1; i<n; i++)
    {
        int next_element = nums[i];
 
        if (data_stack.empty() == false)
        {
            int array_element = data_stack.top();
            data_stack.pop();
 
         while (array_element < next_element)
            {
                cout << array_element << ": " << next_element
                     << endl;
                if (data_stack.empty() == true)
                   break;
                array_element = data_stack.top();
                data_stack.pop();
            }
 
           if (array_element > next_element)
                data_stack.push(array_element);
           }
 
          data_stack.push(next_element);
         }
 
     } 
int main()
{
    int nums[] = {4, 1, 5, 9, 12, 9, 22, 45, 7};
    int n = sizeof(nums)/sizeof(nums[0]);
    cout << "Original array: ";
    for (int i=0; i < n; i++) 
    cout << nums[i] <<" ";
    cout << "\nNext Greater Element:\n";
    next_greater(nums, n);
}

Sample Output:

Original array: 4 1 5 9 12 9 22 45 7
Next Greater Element:
1: 5
4: 5
5: 9
9: 12
9: 22
12: 22
22: 45

Flowchart:

Flowchart: Find the next greater element of every element of a given array of integers

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to find the most occurring element in an array of integers.
Next: Write a C++ program to sort a given unsorted array of integers, in wave form.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Share this Tutorial / Exercise on : Facebook and Twitter