w3resource

C++ Exercises: Count the number of occurrences of given number in a sorted array of integers


20. Count Occurrences of a Given Number in Sorted Array

Write a C++ program to count the number of occurrences of a given number in a sorted array of integers.

Pictorial Presentation:

C++ Exercises: Count the number of occurences of given number in a sorted array of integers

Sample Solution:

C++ Code :

#include <iostream> // Header file for input/output stream
using namespace std; // Using the standard namespace

// Function to count occurrences of a specific number 'x' in an array 'arr' of size 'n'
int count_occurrences(int arr[], int n, int x)
{
    int result = 0; // Variable to store the count of occurrences

    // Loop through each element in the array
    for (int i = 0; i < n; i++)
    {
        // Check if the current element is equal to 'x'
        if (x == arr[i])
            result++; // Increment the count if the element matches 'x'
    }
    return result; // Return the total count of occurrences
}

int main()
{
    int nums[] = {5, 7, 8, 8, 5, 8, 7, 7}; // Declaration and initialization of an integer array
    int n = sizeof(nums) / sizeof(nums[0]); // Calculate the number of elements in the array
    cout << "Original array: ";
    for (int i = 0; i < n; i++) 
    cout << nums[i] << " "; // Output each element of the original array

    int x = 7; // The number to count occurrences of
    cout << "\nNumber of occurrences of 7 : " << count_occurrences(nums, n, x); // Call function to count occurrences of 'x'
    return 0; // Return 0 to indicate successful execution
}

Sample Output:

Original array: 5 7 8 8 5 8 7 7 
Number of occurrences of 7 : 3

Flowchart:

Flowchart: Count the number of occurences of given number in a sorted array of integers

For more Practice: Solve these Related Problems:

  • Write a C++ program to count how many times a specified number appears in a sorted array using binary search to locate its boundaries.
  • Write a C++ program that reads a sorted array and a target number, then outputs its frequency using lower_bound and upper_bound.
  • Write a C++ program to find the count of a given element in a sorted array by iterating through the array and incrementing a counter.
  • Write a C++ program that employs a modified binary search to efficiently count occurrences of a number in a sorted sequence.

Go to:


PREV : Find Element Occurring Odd Number of Times.
NEXT : Find Two Repeating Elements in Array.

C++ Code Editor:



Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.