C / How to exchange for a while?

Asked

Viewed 799 times

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);
}

Complete

#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);
 }
  • 2

    You understood what the for are you doing? Could you describe with words?

  • Yes, I will post the full code.

  • 3

    But the question I asked was "Could you describe in words what you understood about the function of for in that code", not "please post the full code", although possibly it will be better with the full code.

1 answer

4


The difference between the for and the while, is that the for allows you to assign and declare variables only within that scope, so the for will perform both the condition check and the "indicator" update automatically, no need to place within the scope

while will only check a simple condition and already go to the scope, so any assignment or variable statement should be made after the format

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;
    }
 }
  • I think your code answers the question, yes; just an observation that it’s possible to both use scope variables "extra for" as only in the scope "inside the while", but that would be another discussion :P anyway, there are several interesting readings on scope of variables, like this

  • Correct! only the dot and comma after the NULL error, removed and all right while(r!= NULL;)...

Browser other questions tagged

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