How to Print All Distinct Elements in an Array in C

How to Print All Distinct Elements in an Array in C

How to Print All Distinct Elements in an Array in C

Identifying and printing distinct elements in an array is a fundamental programming task. Distinct elements are the unique (non-duplicate) values in the array. This article provides a clear explanation, a step-by-step algorithm, and a C program to achieve this.Print All Distinct Elements in an Array in C

Table of Contents

  1. Introduction
  2. What Are Distinct Elements?
  3. Algorithm to Find Distinct Elements in an Array
  4. C Program to Print Distinct Elements
  5. Conclusion
  6. Suggested Programs

1. Introduction

Printing distinct elements from an array is a common task in programming that demonstrates the ability to work with arrays and basic algorithms. This tutorial guides you through a simple yet effective way to identify and print distinct elements.

2. What Are Distinct Elements?

  • Definition: Distinct elements are those that occur only once in the array, without any duplicates.
  • Example:
    • Input: 2, 3, 4, 5, 6, 1, 2, 3, 4
    • Output: 5, 6, 1

3. Algorithm to Find Distinct Elements in an Array

  1. Input the array size and elements.
  2. Iterate through the array.
    • For each element, check if it appears elsewhere in the array.
  3. Print the element if it is not found again.

4. C Program to Print Distinct Elements

#include <stdio.h>

void printDistinctElements(int arr[], int size) {
    printf("Distinct elements in the array are: ");
    for (int i = 0; i < size; i++) {
        int isDistinct = 1;
        for (int j = 0; j < size; j++) {
            if (arr[i] == arr[j] && i != j) {
                isDistinct = 0;
                break;
            }
        }
        if (isDistinct) {
            printf("%d ", arr[i]);
        }
    }
    printf("\n");
}

int main() {
    int n;

    // Input size of the array
    printf("Enter the size of the array: ");
    scanf("%d", &n);

    int arr[n];

    // Input array elements
    printf("Enter %d elements of the array: ", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    // Print distinct elements
    printDistinctElements(arr, n);

    return 0;
}
Sample Input:
Enter the size of the array: 9
Enter 9 elements of the array: 2 3 4 5 6 1 2 3 4
Sample Output:
Distinct elements in the array are: 5 6 1

5. Conclusion

This program effectively identifies and prints distinct elements from an array by leveraging nested loops for comparison. While this approach works well for small arrays, consider using more advanced techniques like hash maps for larger datasets to optimize performance.Print All Distinct Elements in an Array in C