c code for next greater element

  • cNGE
  • write code for next greater element in c

    2. Given a dynamic array, WAP prints the next greater element (NGE) for every element. The next greater element for an element x is the first greater element on the right side of x in the array. For elements for which no greater element exist, consider the next greater element as -1. E.g. For the input array [2, 5, 3, 9, 7], the next greater elements for each element are as follows.

    Code

    #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> void printarray(int *arr, int n) { for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); } void nge(int *arr, int n) { for (int i = 0; i < n; i++) { int j; check: j = i + 1; while(j < n) { if (arr[j] > arr[i]) { printf("%d %d\n", arr[i], arr[j]); i++; goto check; } j++; } printf("%d %d\n", arr[i],-1); } } int main() { int n, a, b; printf("enter the total elements of array\n"); scanf("%d", &n); int *arr = (int *)malloc(n * (sizeof(int))); for (int i; i < n; i++) { printf("enter the element %d :\n", i + 1); scanf("%d", &arr[i]); } printarray(arr, n); nge(arr, n); return 0; }