Vector without repeated numbers in C

Asked

Viewed 5,419 times

0

How do I load an array, let the user enter all values, which cannot have repeated numbers?

For example, a vector of 20 positions that asks the user to enter each value, and, when giving a value equal to any previous one, a message would appear and it would be necessary to inform another value.

My code so far:

main()
{
    printf("Insira os dados do vetor A\n");

    for(i = 0; 20 > i; i++)
    {
        scanf("%d",va[i]);
        auxva = va[i];

        for(j = 0; 20 > j; j++)
        { 
            if (va[j] == auxva)
            {
                printf("Sem valores repetidos\n");
                scanf("%d",&auxva);
            }

            if(va[j] != auxva) 
                continue;
        } 
    } 
} 
  • 1

    At each given value, you will need to traverse the entire current vector by checking whether the value matches at least one value present in the vector. If yes, re-request the number, if not, insert it. Do you have any attempt that did and went wrong?

  • main(){ printf("Enter vector data A n"); for(i=0;20>i;i++){ scanf("%d",va[i]); auxva = va[i]; for(j=0;20>j;j++){ if (va[j]==auxva){ printf("No repeat values n"); scanf("%d",&auxva); } if(va[j]!=auxva) continue; } } } I had done something like this, I’m still a little lost, but I think the idea is more or less right, thanks!

  • Beto, I added your code directly to the question. Since it’s new here, I recommend you do the [tour] to understand the basics of how the site works. There you will find everything you need to use the site well, such as tips on how to ask, how to format questions and answers, etc.

  • Three comments: 1. You have not declared any variable in your example, so it has no way to compile. 2. that if (va[j] != auxva) continue; is redundant: if you take it out completely does not change the behavior of the code. 3. It was your teacher that she taught to write 20 > i and 20 > j in the bonds for?

4 answers

1

You can do it like this:

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

int exists(int *numbers, int size, int n) {
    for (register int i = 0; i < size; i++) {
        if (numbers[i] == n)
            return 1;
    }

    return 0;
}

void printArray(int *numbers, int size) {
    for (register int i = 0; i < size; i++)
        printf("%d ", numbers[i]);
    printf("\n");
}

int main(int argc, char *argv[]) {
    int size = 20;
    int *numbers = (int *) malloc(sizeof(int) * size);
    int count = 0;
    int n;

    while (count < size) {
        printf("Digite um número!\n");
        scanf("%d", &n);

        if (exists(numbers, size, n) == 0) {
            printf("Inserindo número no array\n");
            numbers[count] = n;
            count++;
        } else {
            printf("Número já existe\n");
        }
    }

    printf("O array é:\n");
    printArray(numbers, size);
}
  • So buddy, I haven’t gotten to the arrays part yet, my subject is at the beginning of vectors in C. Is there any solution using only basic concepts like repetition structures?

  • In this example I am using only a one-dimensional vector and repeating structures. :)

1

#include <cstdio>

int vetorA[4];
int i, k;

int main()
{
    printf("\nDigite 4 elementos para o Conjunto A:\n");
    for(i=0;i<4;i++){//Carregando o vetor
        printf("Digite o valor %d: ", i+1);
        scanf("%d", &vetorA[i]);

        for(k=0;k<=i-1;k++){//Verificando se o valor já digitado antes
            if(vetorA[i]==vetorA[k]){
                printf("Valor %d ja exite no Conjunto\n", vetorA[i]);
                i-=1;
            }
        }
    }
    printf("\nConjunto A = { ");//Imprimindo o conjunto

    for(i=0;i<4;i++){
        printf("%d, ", vetorA[i]);
    }
        printf("}\n");
}

0

#include <stdio.h>

#define TAM_VETOR 5

int main()
{
    int vetor[TAM_VETOR] = {0};//zera tudo que tive la dentro
    int qtdInseridos = 0;//Quantos numeros ja foram inseridos
    int n;//valor que o cara coloca

    register int a;//contadores de loop


    for( ; qtdInseridos < TAM_VETOR; )
    {
        scanf("%d", &n);

        for(a = 0; a < qtdInseridos; a++)
            if( vetor[a] == n )
                break;

        if( a == qtdInseridos ) //passou por todo o for sem encontra nenhum numero igual a N, logo "a" é igual "qtdInseridos"
            vetor[qtdInseridos++] = n;
        else
            printf("Numero repetido.\n");

    }

    //Printa o vetor
    for(a = 0; a < TAM_VETOR; a++)
        printf("%d ", vetor[a]);
    printf("\n");

    return (0);
}
  • If you’re gonna do for (; qtdInseridos < TAM_VETOR; ), better do while (qtdInseridos < TAM_VETOR), instead.

  • @Wtrmute aew is already a matter of taste

0

//Codigo Simples
#include <stdio.h>

int main(){

    int i,j,n,vetor[20];

    int bandeira = 0;
    for(i = 0; i < 5; i++){
        scanf("%d", &n);
        //verifica se o numero digitato é igual a algum anterior
        for(j = 0; j <= i-1 ; j++){
            if(n == vetor[j]){
                bandeira = 1;
                //Caso encontre, a bandeira recebe 1 e o
                //"for" verificador é quebrado para economizar
                //processamento.
                break;
            }
        }
        //Se a bandeira é igual a 1, isso
        //significa que existe um numero igual
        if(bandeira == 1){
            printf("%d repetido \n", n);
            bandeira = 0;
            //A variavel "i" recebe menos 1, para garantir que o "i"
            // só vai referenciar a próxima posição do vetor quando o
            //usuário NÃO digitar um número repetido.
            //A bandeira é zerada para poder ser reutilizada.
            i -= 1;
        }else{
            //Caso não houver numero repetido, o numero é colocado
            //no vetor.
            vetor[i] = n;
        }
    }

    //Mostrar o vetor.

    for(i = 0; i < 5; i++){
        printf("%d ", vetor[i]);
    }

    return 0;
}

Browser other questions tagged

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