How to verify that all elements of a vector are between - 4 and 4?

Asked

Viewed 125 times

0

I want to compare whether all elements of an array are between -4 and 4, if so, the algorithm will execute the method.

for(int i=0; i< j; i++){

   if(vet[i] > -4 && vet[i] <4)

   calcular(4);

}
  • In what language? Do not use tags than you don’t want.

  • Anyone. I just want to see the logic.

  • What would be the doubt? It seems to me that the condition is correct.

  • Got it now. You want to check all.

  • That msm...................

  • 2

    It will be easier to limit the scope in just one language. Possible solutions for each language can vary greatly.

Show 1 more comment

1 answer

3


It is easier to reverse the condition and exit quickly if you have an element that does not fit in the filter, like this:

#include <stdio.h>

void filtro(int tamanho, int vet[]) {
    for (int i = 0; i < tamanho; i++) if (vet[i] <= -4 || vet[i] >= 4) return;
    printf("Está executando um método\n");
}
int main(void) {
    int vet[] = { 1, 2, 3, 4 };
    filtro(3, vet); //não considerará o último elemento que não encaixa no filtro
    printf("Agora não vai passar pelo filtro");
    filtro(4, vet);
}

See working on ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

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