How do I use if inside the for, without the outside if appearing?

Asked

Viewed 799 times

0

printf("\nDigite o usuario que deseja pesquisa, pela Matricula: \n");
gets(strL);
busca=atoi(strL);
for(i=0; i<quant; i++) {
    if(busca==dados[i].matricula) {
        printf("Aluno: %d\n",i);
        printf("Nome: %s\n",dados[i].nome);
        printf("CPF: %s\n",dados[i].cpf);
        printf("Matricula: %d\n",dados[i].matricula);
        printf("Idade: %d\n",dados[i].idade);
        printf("\n-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-\n");
    }
}
    if(busca!=dados[i].matricula) {
       printf("pesquisa invalida, tente novamente! \n");
    }

The code compile normally. The problem is that the first if is for when it’s equal and the second is for when for different and in this case when I compile both the if inside as far as outside the for, and executed, of which only one is true.

printf("pesquisa invalidade invalidade, tente novamente");

  • Note that when you close the loop for the value of the variable i will be quant and therefore the if condition after the loop will almost certainly be false, because you are accessing a position outside the limits of the array. Turn on a flag if you find or close the loop when you find it (maybe in this case a while is better).

  • Another possibility is you put one break; at the end of the if internal to the loop, ie exit from the loop when finding but, even in that case, it is best to check whether i >= quant to inform that you have not found.

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

1

The best way is using a function since without it would have to create a flag that is gambiarra, and the function better isolates what is each thing.

You want it to show the user if they find it and then close it with nothing else, or if they searched all users and didn’t find a piece of data you want a message to indicate that, so:

void mostraUsuario(int codigo) {
    for (int i = 0; i < quant; i++) {
        if (dados[i].matricula == codigo) {
            printf("Aluno: %d\n",i);
            printf("Nome: %s\n",dados[i].nome);
            printf("CPF: %s\n",dados[i].cpf);
            printf("Matricula: %d\n",dados[i].matricula);
            printf("Idade: %d\n",dados[i].idade);
            printf("\n-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-\n");
            return;
        }
        printf("pesquisa invalida, tente novamente! \n");
        return;
    }
}

I put in the Github for future reference.

There are other problems in the code, even without seeing all of it, but it will work in one exercise, so I won’t try to solve.

Browser other questions tagged

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