How do I output my array’s Indice in C?

Asked

Viewed 117 times

1

I have a program that will check 9 numbers and tell which one is the biggest of all, and for this I am using vetor already filled with values, and I’m using a for to go through the whole vetor and search for the largest. The problem is that I’m not able to show which index number is the largest of all.

My code :

setlocale(LC_ALL,"portuguese");

    int bolas[9] = {0,0,0,0,20,0,0,0,0};

    for(int i = 0; i < 9; i++) {
        if(bolas[i] > bolas[i+1]) {
            printf("A bola %d é maior que todas as outras. ",bolas[i]);
        }
    }

In this code, in the printf it will show the size of the number, not its position in the index, I need to show the position and not the size. How can I do this ?

1 answer

3


if you’re giving the printf within the for, he is typing several times the message. what you need to do is, first find out which index has the highest value, and then the for make the impression (printf). Example:

int bolas[9] = {0,0,0,0,20,0,0,0,0};
int maior = 0;
int i = 1;
for(i = 1; i < 9; i++) {
    if(bolas[i] > bolas[maior]) {
        maior = i;
    }
}

printf("A bola %d é maior que todas as outras. ",bolas[maior]);

or if you want to print only the index, not the value of the ball:

printf("A bola %d é maior que todas as outras. ",maior);
  • It does not work your code, it returns the same thing as mine. See working : http://ideone.com/UBrrhy.

  • Want the index? Have it written maior, because this is the index of the largest element of the vector

  • 1

    works!, stdout: A bola 20 é maior que todas as outras.

  • 1

    see the change in response

  • Thanks, it worked even, only a correction, as the index of the array starts with 0, you have to put +1 in the largest to give the true index.

  • 1

    printf("Ball[%d] = %d eh the largest of all", largest, ball[largest]) will display both the index and the largest element, @Monteiro

  • @Mount indexes start at 0 or 1? In fact, it depends on the semantic set you are working on, so for the semantic set vector c, the given solution is fully correct

  • in fact, the true index would continue to start with 0 né...rs but if the user wants to display by 1, ok, just add +1 to the index

  • but it’s cool, I was about 4 years old who did not mess with c rsrs

  • Thanks guys, I’m new to C, so fine, I’ll take your word for it because you have more experience than I do. And it worked right the code. + 1 and right answer.

Show 5 more comments

Browser other questions tagged

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