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

Asked

Viewed 42 times

0

Boa am doing the following exercise in C language inserir a descrição da imagem aqui

I made the following code and I don’t understand why it’s not working...

int maior_subida(int *tab, int dim) {
int i, 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;
    }
}
return pos;}

int main(){
int tabela[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: inserir a descrição da imagem aqui

1 answer

2


There are some flaws in your code, for example:

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

  2. 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 visualize, in which case it would be the tab[i];

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

  4. and another thing that could be improved would be the elimination of the differentia_previous variable, as its return should be from the position in which occurs the described in the question, so it is unnecessary to keep the difference in each execution of the loop.

Here I leave your code with the changes I mentioned, observe the changes and apply the tips on next 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;
}
  • Thanks for the answer, really not repaired in the possibility of bufferOverflow, already fixed my algorithm and the program works correctly. Regarding what I said in point 2, I am learning to manipulate pointers so the choice to use *tab instead of tab[0]

Browser other questions tagged

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