Number of indexes with equal elements in given range in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that counts the number of indexes with equal elements in the given range.

You are given an array, and indexes range. You need to count the total number of adjacent elements that are equal in the given range.

Let's see the steps to solve the problem.

  • Initialise the array and indexes range.

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

    • Compare the element the previous or next element.

    • Increment the count if they are equal.

  • Return the count.

Example

Let's see the code.

 Live Demo

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

Output

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

10

Conclusion

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

raja
Published on 03-Jul-2021 05:23:46
Advertisements