Functions with parameters in c language

Asked

Viewed 171 times

0

I need help to solve the following problem:

"Write a function that receives an arrangement of whole as parameter and returns the index of the largest element of the arrangement. Ex : int intMax(int *a, int tamanho)"

I made a part of the code and it does what was asked, only not the way it was asked:

int recebeArray(){
  int mtrx[5];
  int count, maior;

  for(count=0; count<5; count++){
    printf("Digite um numero \n");
    scanf("%d",&mtrx[count]);

    if(mtrx[count] > mtrx[count-1]){        
      maior=mtrx[count];
    }           
  }

  printf("O maior numero e' : %d",maior);
}

int main(){
  recebeArray();
}

1 answer

3

You need to go through all the elements of the vector, storing in an auxiliary variable the index that contains the highest value ever found, for example:

#include <stdio.h>

int intMax( int *a, int tamanho )
{
    int i, max = 0;
    for( i = 1; i < tamanho; i++ )
        if( a[i] > a[max] )
            max = i;
    return max;
}

int main( void )
{
    int foobar[8] = { 4, 10, 2, 13, 3, 7, 1, 0 };
    int i = intMax( foobar, 8 );
    printf( "foobar[%d] = %d\n", i, foobar[i] );
    return 0;
}

Exit:

foobar[3] = 13
  • 1

    Wouldn’t it be better to i of for start right at 1 ?

  • @Isac: You’re right! It’s not necessary to sweep the array from the first element (i = 0), scan can start from the second element (i = 1), if he exists.

  • @Isac: Really, if you consider the first element as the biggest one today, it doesn’t make sense to go through it again.

Browser other questions tagged

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