C / How to change the for for a while?

1

Write the function prints using the while repeat structure instead of for. If necessary I can edit and insert all the code.

void imprime(Ccc *p)
{
    Ccc *r;
    for (r = p; r!=NULL; r = r->proximo)
        printf("%c",r->caracter);
}

Full

#include <stdio.h>
#include <stdlib.h>

typedef struct ccc {
    char caracter;
    struct ccc *proximo;
} Ccc;

void imprime(Ccc *p)
{
    Ccc *r;
    for (r = p; r!=NULL; r = r->proximo)
        printf("%c",r->caracter);
}

void liberar_memoria(Ccc *p)
{
    Ccc *q, *r;
    q = p;
    while (q!=NULL) {
        r = q->proximo;
        free(q);
        q = r;
    }
}

main()
{
    Ccc *p1, *p2, *p3;

    p1=(Ccc *)malloc(sizeof(Ccc));
    p2=(Ccc *)malloc(sizeof(Ccc));
    p3=(Ccc *)malloc(sizeof(Ccc));

    if ((p1==NULL)||(p2==NULL)||(p3==NULL)) 
        return;

    p1->caracter='A';
    p1->proximo=p2;

    p2->caracter='L';
    p2->proximo=p3;

    p3->caracter='O';
    p3->proximo=NULL;

    imprime(p1);
    liberar_memoria(p1);
 }
    
asked by anonymous 29.08.2018 / 14:25

1 answer

4

The difference between the for and the while, is that the for allows assignment and declaration of variables only within that scope, so the for will perform both verification of the condition and the update of the "indicator" automatically, not being necessary to place within the scope

Since while will only check for a simple condition and will already be in scope, then any assignment or variable declaration must be made after the

while (condição){ 
   (escopo);
}

Then your code will be:

 void imprime(Ccc *p){
    Ccc *r;
    r = p;
    while(r!=NULL;){
      printf("%c",r->caracter);
      r = r->proximo;
    }
 }
    
29.08.2018 / 14:49