Highest value in a fixed vector of 10 positions

Asked

Viewed 248 times

1

I have pending exercise to find the largest element in a fixed vector of 10 elements. However, when declaring the array integers works, but when I ask the user to enter the values 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);
  • 1

    It would be because it is using the smaller operator to check if it is bigger?

  • 1

    For what you’re trying to do you don’t need the array, and it turns out to be the reason why it doesn’t work

  • I saw it just now, but my doubt is because I’m initiating the matrix with the right input values to show the biggest ?

  • for me it was supposed to work, Getting bigger with the first element of the vector and testing so on

1 answer

3


You are sending the value of v[0] for the variable maior, without even defining some value for it, soon goes 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, soon at the end will print that number.

Could use putting in the variable maior the value of -1, if only read positive numbers, but it would not be the best option too.


You can do as follows:

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);

Browser other questions tagged

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