Determine the position where the highest value increase occurs in an array

0

I'm doing the following exercise in C language

ImadethefollowingcodeandIdonotunderstandwhyitisnotworking...

intmaior_subida(int*tab,intdim){inti,pos=0,diferenca=0,diferenca_anterior=0;for(i=0;i<dim;i++){diferenca=((*(tab+i+1))-(*(tab+i)));if(diferenca>diferenca_anterior){pos=(i+1);diferenca_anterior=diferenca;}}returnpos;}intmain(){inttabela[10]={31,3309,43,5,25461,10,9,7,537,1},posicao;posicao=maior_subida(tabela,10);printf("O elemento que tem maior diferenca do anterior e o que esta na posicao: %d\n",posicao);}

With this code I get the following result:

    
asked by anonymous 31.03.2018 / 02:24

1 answer

2

There are some flaws in your code, for example:

  • The difference could already be initialized as difference = tab [1] - tab [0] and pos = 1;

  • Another thing is the use of * (tab + i), in C vectors are pointers, so much so that you can define things like char * string="Hello", always go by the easiest to see, in that if it would be the tab [i];

  • Another error is that your go from 0 to < dim, in the case of dim == 10, its would go from 0 to 9, but when i was 9 and tried to do * (tab + i + 1) it would result in tab + 10, which would cause bufferOverflow and could cause sudden stop of your program;

  • and another thing that could be improved would be the elimination of the variable difference_previous, as its return must be from the position in which the described in the question occurs, so it is unnecessary to save the difference in each execution of the loop. >

  • Here I leave your code with the changes that I quoted, observe the changes and apply the tips in future problems:

    #include<stdio.h>
    
    int maior_subida(int *tab, int dim) {
       int pos=1, diferenca;
       diferenca = tab[1] - tab[0];
       for (int i = 1; i < dim-1; i++) {
          if (diferenca < (tab[i+1] - tab[i]) ){
             diferenca = tab[i+1] - tab[i];
             pos = i+1;
          }
       }
       return pos;
    }
    
    int main(){
       int tabela[10]={31,3309,43,5,25461,10,9,7,537,1}, posicao = 0;
       posicao = maior_subida(tabela,10);
       printf("O elemento que tem maior diferenca do anterior e o que esta na posicao: %d\n",posicao);
       return 0;
    }
    
        
    31.03.2018 / 08:06