Doubt on a C language question

1
  

Write a function that receives a vector of 10 integers and returns to   number of distinct numbers that compose the vector.

For example, if the given vector is v = {3, 2, 1, 3, 4, 1, 5, 5, 2} , the function should return the number 5. And when for example I type from 1 to 10, it returns me 1, if I type 5 numbers 1 and 5 numbers 2, it returns me 5.

#include <stdio.h>
#include <stdlib.h>
#include <locale.h>

#define TAM 10

int difNumbers(int array[], int count) {
    int uniqValue[count];
    int n = 0;

    for(int i = 0; i < count; i++) {
        unsigned char foundUnique = 0;
        for(int x = 0; x < count; x++) {
            if(uniqValue[x] == array[i]) {
                foundUnique = 1;
                break;
            }
        }
        if(foundUnique) {
            uniqValue[n] = array[i];
            n++;
        }
    }

    return n;
}

int main()  {
    setlocale(LC_ALL, "Portuguese");
    int vector[TAM], i;

    for(i = 0; i < TAM; i++) {
        printf("[%d]:", i+1);
        scanf("%d", &vector[i]);
    }
    printf("%d", difNumbers(vector, TAM));
    return 0;
}
    
asked by anonymous 21.09.2018 / 07:00

1 answer

2

The problem starts with the test done at if , here:

if(foundUnique) {

It should actually be the opposite, with operator not :

if(!foundUnique) {
// ^--

Because your foundUnique actually indicates whether the element exists in the new array of unique, and only wants to add if it does not already exist. Another relevant detail is that you are traversing more elements than you should when you try to check if the element exists in the new array of unique:

for(int i = 0; i < count; i++) {
//                   ^---

The count is 10 which is the value sent in main but initially you do not have 10 elements in the array, and as they were not initialized it ends up collecting memory garbage, and can hit a value of those already typed Correct is to go only on the quantity already inserted, with n :

for(int i = 0; i < n; i++) {
//                 ^---

View the code working on Ideone with the two changes mentioned above

    
21.09.2018 / 12:07