Doubt on a Language Issue C

Asked

Viewed 50 times

2

Write a function that takes an array of 10 integers and returns to number of distinct numbers that make up the vector.

For example, if the given vector is v = {3, 2, 1, 3, 4, 1, 5, 5, 2}, the function must return the number 5. And when for example I type from 1 to 10, it turns me 1, if I type 5 numbers 1 and 5 numbers 2, it turns 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;
}

1 answer

2


The problem begins in the test done on if, here:

if(foundUnique) {

It should actually be the opposite, with the Operator not:

if(!foundUnique) {
// ^--

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

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

The count vale 10 which is the value sent in main But initially you don’t have 10 elements in the array, and since they weren’t initialized, you end up picking up junk from memory, and you can hit a value you’ve already typed. Correct is to go only over the quantity already inserted, with n:

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.