Count number of elements between two given elements in array in C++


We are given an array containing integer elements and two numbers start and end and the task is to calculate the count of elements present between start and end in an array.

Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. If the start element is occurring multiple times then we will consider the first occurrence of the start element and if the end element is occurring multiple times then we will consider the end occurrence of the end element.

For Example

Input − int arr[] = {1, 2, 3, 4, 5, 6, 7}
      Start = 1 and End = 7
Output − count is 5

Explanation − In the given array, there are 7 elements and the range is 1-7. So, in between this range there are a total of 5 elements.

Input − int arr[] = {1, 2, 3, 4, 5, 6, 7}
      Start = 7 and End = 9
Output − count is 0

Explanation − In the given array, there are 7 elements and the range is 7-9. So, in between this range there is no element so the count is 0.

Approach used in the below program is as follows

  • Input an array let’s say, int arr[]

  • Calculate the length of both the arrays using the length() function that will return an integer value as per the elements in an array.

  • Start the loop from i to 0 till i less than size of an array

  • Inside the loop, check if arr[i] = start then break

  • Check if i>size-1 then return

  • Start another loop with j to size-1 and j>=i+1 and j--

  • Check if arr[j]=end then break

  • Check if j=1 then return 0

  • Return j-i-1

  • Print the result.

Example

 Live Demo

#include <iostream>
using namespace std;
// For counting the numbers between the two elements
int countelements(int ar[], int n, int start, int end){
   // Find start
   int i = 0;
   for (i = 0; i < n; i++){
      if (ar[i] == start){
         break;
      }
   }
   // If start is not present or present at the last
   if (i >= n-1){
      return 0;
   }
   // Find end
   int j;
   for (j = n-1; j >= i+1; j--){
      if (ar[j] == end){
         break;
      }
   }
   // If end is not present
   if (j == i){
      return 0;
   }
   // number of elements between the two elements
   return (j - i - 1);
}
// Main Function
int main(){
   int ar[] = { 1, 6, 2, 5, 9, 8, 3, 7, 4 };
   int n = sizeof(ar) / sizeof(ar[0]);
   int start = 5, end = 4;
   cout <<"count is " <<countelements(ar, n, start, end);
   return 0;
}

Output

If we run the above code we will get the following output −

count is 4

Updated on: 15-May-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements