How to check if all elements of a vector are between 4 and 4?

0

I want to compare if all elements of a vector are between -4 and 4, if it is, the algorithm will execute the method.

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

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

   calcular(4);

}
    
asked by anonymous 23.11.2017 / 01:46

1 answer

3

It's easier to invert the condition and quit fast 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 no Coding Ground . Also put it in GitHub for future reference .

    
23.11.2017 / 01:57