w3resource

 

C Exercises: Count all distinct pairs for a specific difference

C Array: Exercise-80 with Solution

Write a program in C to count all distinct pairs for a specific difference.

Expected Output:
The given array is:
5 2 3 7 6 4 9 8
The distinct pairs for difference 5 are: [7, 2] [8, 3] [9, 4]
Number of distinct pairs for difference 5 are: 3

The task is to write a C program that counts all distinct pairs of elements in an array that have a specific difference. The program should iterate through the array to find pairs where the absolute difference between the elements matches the given value. The output should display the distinct pairs and the total number of such pairs.

Sample Solution:

C Code:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX 1000000

// Comparison function for qsort
int cmpfunc(const void * arr1, const void * b) {
    return (*(int*)arr1 - *(int*)b);
}

int main() {
    int n, k; // Variables to hold array size and difference value
    int ctr = 0; // Counter for distinct pairs
    int i;
    int arr1[] = {5, 2, 3, 7, 6, 4, 9, 8}; // Given array
    n = sizeof(arr1) / sizeof(arr1[0]); // Calculate array size
    k = 5; // Given difference value

    // Print original array
    printf("The given array is:  \n");
    for (i = 0; i < n; i++) {
        printf("%d  ", arr1[i]);
    }
    printf("\n");

    // Sort the array using qsort function
    qsort(arr1, n, sizeof(int), cmpfunc);

    int l = 0; // Left pointer for the pair
    int r = 0; // Right pointer for the pair

    // Find distinct pairs with difference equal to 'k'
    printf("The distinct pairs for difference %d are: ", k);
    while (r < n) {
        if (arr1[r] - arr1[l] == k) {
            printf("[%d, %d] ", arr1[r], arr1[l]); // Print the pair
            ctr++; // Increment counter for distinct pairs
            l++;
            r++;
        } else if (arr1[r] - arr1[l] > k) {
            l++; // Increment left pointer
        } else {
            r++; // Increment right pointer
        }
    }
    printf("\nNumber of distinct pairs for difference %d are: %d", k, ctr); // Print total distinct pairs
    return 0;
}

Output:

The given array is:  
5  2  3  7  6  4  9  8  
The distinct pairs for difference 5 are: [7, 2] [8, 3] [9, 4] 
Number of distinct pairs for difference 5 are: 3 

Pictorial Presentation:

C Exercises: Count all distinct pairs for a specific difference.

Flowchart:

Flowchart: Count all distinct pairs for a specific difference.

C Programming Code Editor:

Previous: Write a program in C to sort n numbers in range from 0 to n^2.
Next: The array range is [0..n-1] and the elements are in the range [0..k-1] and k<=n.

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.