How to replace / optimize multiple ifs in C?

0

I'm a beginner in C language, I'm doing an activity that is to enroll students and averages in a double-chained list, everything is working, but I believe I'm using too many ifs, is there any way to do these conditions without using as many ifs?

Part of the code:

int editar(aluno *alunoPtr){
aluno *tmp;
int edita, aux=0;
tmp=alunoPtr->prox;
if(vazia(alunoPtr)){
    printf("A LISTA ESTA VAZIA!!!\n");
}else{
    printf("Numero de matricula: ");
    scanf("%i", &edita);
    while(tmp){
        if(edita == tmp->matricula){
            printf("\nMedia final: ");
            scanf("%f", &tmp->mediaFinal);
            if(tmp->mediaFinal >= 0 && tmp->mediaFinal <= 10){
                printf("\nMEDIA CADASTRADA COM SUCESSO!\n");
            }else{
                printf("\nMEDIA INVALIDA!\n");
            };
            aux++;
            break;
        };
        tmp=tmp->prox;
    };
    if(aux==0){
        printf("\nNUMERO DE MATRICULA INVALIDO!\n");
    };
};

};

    
asked by anonymous 16.07.2017 / 05:59

1 answer

0

Using the return to return aux when editing is performed with success and -1 when an error occurs it is possible to remove the last if and some else s.

   int editar(aluno *alunoPtr) {
     aluno *tmp;
     int edita, aux = 0;
     tmp = alunoPtr->prox;
     if (vazia(alunoPtr)) {
       printf("A LISTA ESTA VAZIA!!!\n");
       return -1;
     }
     printf("Numero de matricula: ");
     scanf("%i", &edita);
     while (tmp) {
       if (edita == tmp->matricula) {
         printf("\nMedia final: ");
         scanf("%f", &tmp->mediaFinal);
         aux++;
         if (tmp->mediaFinal >= 0 && tmp->mediaFinal <= 10) {
           printf("\nMEDIA CADASTRADA COM SUCESSO!\n");
           return aux;
         } 
         printf("\nMEDIA INVALIDA!\n");
         return -1;
       };
       tmp=tmp->prox;
     };
     printf("\nNUMERO DE MATRICULA INVALIDO!\n");
     return -1;
   };
    
16.07.2017 / 07:01