Highest value in a fixed vector of 10 positions

1

I am with pending exercise to find the largest element in a fixed vector of 10 elements. But when I declare the integer of the vector works, but when I ask the user to enter the values it does not work.

int i, v[10];
int maior = v[0];
for(i = 1; i < 10; i++){
    scanf("%d", &v[i]);
    if(maior < v[i])
        maior = v[i];
}
printf("Maior = %d\n", maior);
    
asked by anonymous 21.10.2018 / 22:06

1 answer

3

You are sending the value of v[0] to the variable maior , without even setting some value for it, then a value that can not control.

Imagine that v[0] has the value of 403234 , when writing values less than this value in scanf will never change maior , at the end it will give print of that number.

You could use the value of -1 in the variable maior if it only reads positive numbers, but it would not be the best option either.

You can do this:

int i, v[10];
int maior;
for(i = 0; i < 10; i++){
    scanf("%d", &v[i]);
    if(i==0)
        maior=v[i];
    else if(maior < v[i])
        maior = v[i];
}
printf("Maior = %d\n", maior);
    
21.10.2018 / 22:24