Program C exclude vector value and decrease it in one unit

Asked

Viewed 129 times

-1

Staff with a following problem I have to make a program that implements a routine that le 10 numbers of a vector and then receives a value to be searched in the vector if it finds erases this value and decreases the size of the vector in a unit, I tried the following code at a friend’s suggestion to implement a secondary vector to receive the reduced vector, but it’s not working, someone give me a help

#include <stdio.h>
#include <stdlib.h>
int main(){
    int vet[10],vet2[9];
    int val;

    printf("\nDigite os valores do vetor: ");
    for(int i=0;i<10;i++){

        scanf("%d",&vet[i]);
    }
    printf("Digite o valor a ser pesquisado e exluido: ");
    scanf("%d",&val);
    for(int i=0;i<10;i++){
        if(val==vet[i]){
            vet[i+1];
        }
        else{
            vet2[i]=vet[i];
        }
    }
    for(int i=0;i<9;i++){
        printf("%d\n", vet2[i]);
    }
return 0;
}

1 answer

0


The problem is that you use the i of a for that will rotate 10 times in a vector that only has 9 positions, you have to use a variable other than i, one that increments only up to 9.
I could be like this for example:

    for(int i=0,j=0;i<10;i++)
    {
      if(vet[i]!=val)
      {
        vet2[j]=vet[i];
        j++;
      }
    }
  • Look it worked right, I had forgotten this issue of indices, thank you.

  • You’re welcome. But by the logic that you implement, likely to give some error if the vector has repeated values and one of these repeated values is deleted

  • Good, and truth plus the statement does not quote repetitions

Browser other questions tagged

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