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]);
}
}
Why are you comparing it to
vetor[i+1]
if you haven’t even allocated anything there yet?– Rafael Tavares
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– Ricardo Pontual
I understand your comments, @Ricardopunctual Punctual. I will review my code, thank you
– Wesley Franklin
first you can try something simpler like
if(vetor[i]>maior) { maior = vetor[i]}
:)– Ricardo Pontual
@Ricardopontual I drew, really simpler.
– Wesley Franklin