How do I do this with the loop while
?
void imprime(lista* recebida){
lista* aux;
for(aux=recebida; aux!=NULL; aux=aux->prox){
printf("Informacao %d\n",aux->info);
}
}
How do I do this with the loop while
?
void imprime(lista* recebida){
lista* aux;
for(aux=recebida; aux!=NULL; aux=aux->prox){
printf("Informacao %d\n",aux->info);
}
}
You should use what is most appropriate for each situation. The for
may look like a while
, and it's until you start using continue
, there's a difference because in for
o statemnet that should be executed in each repetition will always be executed no matter what happens, whereas in while
a continue
will cause it not to run, and probably not what you want. In this case it does not have continue
so it will work.
The for
is made up of three parts, the first one is a initialization, so just put it before everything, the second is the condition and it is to be placed in while
, and finally the last is the "step", which must be repeated every time and you must put within the while
in the last line of the execution block.
void imprime(lista* recebida) {
lista* aux = recebida;
while (aux!=NULL) {
printf("Informacao %d\n",aux->info);
aux=aux->prox;
}
}
I placed it on GitHub for future reference .
You have other questions about it:
for
is a type of loop that is more convenient than while
, but this and do while
are more primitive than the first.
As you can see, for
is made up of four "parts":
for («inicialização»; «teste»; «pós-passo») { «corpo do laço» }
The for
then executes «initialization» once, and then checks the result of «test» : if it is nonzero, execute « body of the loop »and « step-by-step » once each in this order, and will again check the result of « test », by executing "Body of the loop" and «step-by-step» until «test» give zero. Then it continues execution after the end of for
.
Using while
, therefore, we would have the following structure equivalent:
«inicialização»; while («teste») { «corpo do laço»; «pós-passo» }
Using goto
:
«inicialização»;
label1:
if (!«teste») goto label2;
«corpo do laço»;
«pós-passo»;
goto label1;
label2:
Why use for
, so if while
is good? Because the programmer, when using while
, has to be careful to ensure that he writes the "step-by-step" , or runs the risk of causing an infinite loop, since the which usually modifies the state of the program to ensure that the loop usually ends. In for
you write as soon as you start writing the structure and therefore tend not to forget this detail. But sometimes the body of the tie is already in charge of ensuring that we will not be inspecting the same item forever.
Syntax:
while (condição)
{
Instrução ou bloco de instruções;
}
Performs the repetition of an instruction block while a condition is true.
Source: link
In your case you could do something like this:
void imprime(lista* recebida){
lista* aux;
aux=aux->prox;
while(aux!=NULL){
printf("Informacao %d\n",aux->info);
aux=aux->prox;
}
}