I wonder why my code doesn’t work, I believe my logic is correct, but it’s picking up garbage

Asked

Viewed 59 times

-1

I will receive 5 values in the vector, I have to add the largest of them to the smallest of them, What’s wrong with it? follows my code.

#include <stdio.h>

int main(){
    int vetor[5];
    int i  = 0;
    int maior = 0, menor = 0, soma = 0;
    for(i = 0; i<5;i++){
        scanf("%d", &vetor[i]);
        if(vetor[i+1]>vetor[i]){
            maior = vetor[i+1];
        }
        else if(vetor[i+1]<vetor[i]){
            menor = vetor[i+1];
        }
    }
    
    
    soma = maior + menor;
    printf("%d", soma);

}
  • 3

    Why are you comparing it to vetor[i+1] if you haven’t even allocated anything there yet?

  • 3

    off what @Rafaeltavares commented, when it is in the last value of variable i, which is 4, vetor[i+1] this will give error, will be trying to read a value out of the size of your vector

  • I understand your comments, @Ricardopunctual Punctual. I will review my code, thank you

  • first you can try something simpler like if(vetor[i]>maior) { maior = vetor[i]} :)

  • @Ricardopontual I drew, really simpler.

1 answer

0


Yes one of the biggest problems of your code was the memory junk that was entering the smallest, because as it was inside an ELSE IF, if you only put numbers bigger than the first number, it would be useless. (ps: your first number always has to be the largest and the smallest at the same time)

To escape from this problem, you use the maximum value of int for the smallest and maximum value of int negative for the largest.

Besides, for practicality, when comparing which is the highest and lowest value, it is ideal to use the variable of greater and lesser than you declared, because you only compared with vector i+1, which is so in the end, you would compare with nothing.

Follow the corrected code.

#include <stdio.h>
int main(){
    int vetor[5];
    int i  = 0;
    int maior = -2147483648, menor = 2147483647, soma = 0;
    
    for(i = 0; i<5;i++){
        printf("Valor [%d] -> ",i);
        scanf("%d", &vetor[i]);
        
        if(vetor[i]>maior){
            maior = vetor[i];
            printf("maior says: novo maior %d\n",maior);
        }
        if(vetor[i]<menor){
            menor = vetor[i];
            printf("menor says: novo menor %d\n",menor);
        }
    }
    soma = maior + menor;
    printf("\n\nSoma do maior e do menor: %d\n", soma);

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

Browser other questions tagged

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