Home > OS >  Print values that occur at least once in an array in C
Print values that occur at least once in an array in C

Time:04-28

In the program, I form an array that looks something like this:

unsigned short types[] = {1,1,2,3,4,100,7,8,1,1};

I need to find and output the number of unique values that occur in an array. For this example, the unique values are: 1,2,3,4,100,7,8 and there are only 7 of them. That is, the program should display:

total number of unique values in the given array - 7.

The range of possible values in the array is 0-0xFF (0 - 255). The size of the array types is 65535. The array can be modified and anything can be done with it to get an answer, but it is desirable that the complexity of the calculations is not great. How can this be done in C?

CodePudding user response:

Following @wohlstad 's comment on the question, this following function would take the array and its size as parameters, and print the answer:
Edit: added a main to show example of use and changed the return so it can more easily handle errors, in case something was unclear for the user asking the question.

#include <stdio.h>

int print_unique_values_in_array(unsigned short* array, int len) {
   
   if (len <= 0 || array == NULL) {
       // error message
       return -1;
   }

   int occurrences[256] = {0}; // initialize all values to 0.

   for (int i=0; i < len; i  ) {
       if (array[i] > 255 || array[i] < 0) {
           // error message
           return -1;
       }
       occurrences[array[i]]  = 1;
   }
   
   int unique_occurrences = 0;

   for (int i=0; i < 256; i  ) {
       if (occurrences[i] == 1)
           unique_occurrences  = 1;
   }
   printf("total number of unique values in the given array - %d\n", unique_occurrences);
   return unique_occurrences;
}


int main() {

    unsigned short types[10] = {1,1,2,3,4,100,7,8,1,1};
    int size = 10;

    int unique_occurrences = print_unique_values_in_array(types, size);
    if (unique_occurrences < 0) {
        // ...
        return 1;
    }
    return 0;
}
  • Related