Number of elements less than or equal to a given number in a given subarray in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that counts the number of element less than or equal to the given number in a given subarray.

You are given a number and subarray lower and upper bound indexes. You need to count number of elements that are less than or equal to the given number.

Let's see the steps to solve the problem.

  • Initialise the array, number, and subarray indexes.

  • Initialise the count to 0.

  • Write a loop that iterates from the lower index of the subarray to the upper index of the subarray.

    • If the current element is less than or equal to the given number, then increment the count.

  • Return the count.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int getElementsCount(int arr[], int n, int lower, int upper, int k) {
   if (lower < 0 || upper >= n || lower > upper) {
      return 0;
   }
   int count = 0;
   for (int i = lower; i <= upper; i++) {
      if (arr[i] <= k) {
         count += 1;
      }
   }
   return count;
}
int main() {
   int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
   int n = 8, k = 4;
   cout << getElementsCount(arr, n, 0, 3, k) << endl;
   cout << getElementsCount(arr, n, 4, 7, k) << endl;
   return 0;
}

Output

If you run the above code, then you will get the following result.

4
0

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 03-Jul-2021 05:10:35
Advertisements