Loops based on a flowchart

1

How do I write code for a loop based on this flowchart? It has do...while . I need a straightforward answer with nested loops.

    
asked by anonymous 02.11.2017 / 03:54

1 answer

7

This flow tells me the following:

  • Run task A
  • Compare B ; if true, get out of the loop
  • Run the task C
  • Go back to step 1
  • Note that the flow in step 4 is an unconditional deviation returning to step 1. This deviation ends up creating an infinite loop (while B is not satisfied). Generally speaking, I would do this:

    while (true) {
      // passo 1
      // passo 2
      // passo 3
    }
    

    Step 4 is represented by the flow control provided by while . Filling in some more gaps, we get:

    while (true) {
      A();
      // passo 2
      C();
    }
    

    Assuming that A() and C() are the methods called in steps 1 and 3. It can be anything but represented by methods.

    On step 2, it involves a conditional in B . There is no case senão . So overall:

    while (true) {
      A();
      if (B()) {
        // ação caso B seja verdadeiro
      }
      C();
    }
    

    The action to exit the loop is with break . Then:

    while (true) {
      A();
      if (B()) {
        break;
      }
      C();
    }
    
      

    Using the language dot to describe your diagram, I got the following:

         

        

    I'mjustrepublishingitherebecauseI'mgoingtousethislanguagetodosomemanipulationinthestructureoftheloopandgenerateotherequivalents,sotheideaistoreduceestrangement.

    Theloopstructureisequivalenttotheexpression:

    AB(CAB)*

    WhydoIsaythis?Simple,becauseAandBareexecutedand,dependingonthatresult,IexecuteC,thenA(returninginloop)andthenBagain,tomakethedecisionwheretostart.p>

    Thefollowingdescriptionisthetranslationoftheexpression.Notethatthisstep-by-stepisequivalenttothefirstone.

  • RuntaskA
  • WhilenotB,do:
  • Run%of%
  • Run%of%
  • Comparedtothepreviousscheme,Ididnotneedmorethanoneunconditionaldeviationstep,Iuseda"while." I copied the command that was before the conditional to the end of the loop, so that it runs at the right time the same amount of times.

    The flowchart is now drawn like this:

    Incode,whileturnsaC.Therestremains:

    A();while(!B()){//percebaqueeusórepitoenquanto'B()'forfalso,jáque'B()'éacondiçãodesaídaC();A();}

    Stillusingflowchart2,wecandousingA.Idonotlikethisalternative,butitworks.

    A();for(;!B();A()){C();}

    Bychangingslightlythewhile,wegetthefollowing:

    A();for(;!B();C(),A());

    Wecanmakeforasaninfiniteloopaswell:

    for(;;C()){A();if(B()){break;}}

    Ifyoumaketoomuchefforttocheckafteroperations,thisoperationmustnecessarilyfollowalloperations.Forthis,wecandefinethattheinitialroutableisjustfor,assigntotheroutabletheexecutionofforandthenAandthendotheconditionalverification:

    Runnablerodavel=()->{A();};do{rodavel.run();rodavel=()->{C();A();};}while(!B());

    WecanalsocontrolthewaytheCoperationisrun.WecancontrolitthroughaflagmnemonicallynamedA,whichstartsasfalsebut,attheendoftheloop,thetruevalueisassignedtoit:

    booleandeveExecutarC=false;do{if(deveExecutarC){C();}A();deveExecutarC=true;}while(!B());

    WecantryassigningtheflagvalueseveraltimesbyplacingthisassignmentwithinblockC:

    booleandeveExecutarC=false;do{if(deveExecutarC){C();}else{deveExecutarC=true;}A();}while(!B());

    Thisproblemcouldbesolvedrecursivelytoo:

    privatevoidexecutaRecursivo(){C();A();if(!B()){executaRecursivo();}}privatevoidfluxograma(){A();if(!B()){executaResursivo();}}

    JustcallthedeveExecutarCmethodandyou'llgetthesameexecution.

    Wecanputtherecursioninadifferentway,passingaparametertoit.Theideaisthesameaselsewiththefluxogramaflag:

    privatevoidfluxograma(booleandeveExecutarC){if(deveExecutarC){C();}A();if(!B()){fluxograma(true);}}privatevoidfluxograma(){fluxograma(false);}

    Togetthedesiredresult,justcalldo-while,withoutarguments.

    Morevariationwithrecursion:

    privatevoidrecursao(){if(!B()){C();A();recursao();}}privatevoidfluxograma(){A();recursao();}

    Asusual,justcalldeveExecutarC.

    Amorefriendlyvariationofthepreviousrecursion:

    privatevoidrecursao(){if(B()){return;}C();A();recursao();}privatevoidfluxograma(){A();recursao();}

    Asusual,justcallfluxograma().

    Anothervariation:

    privatevoidfluxograma(){A();if(B()){return;}C();fluxograma();}

    Asusual,justcallfluxograma().

    Anotherrecursion,inspired in this answer , Indent recursion of function, function pointer :

    private void fluxograma() {
      A();
      Runnable funcaoSaida = B()? () -> {}: () -> { C(); fluxograma(); };
      funcaoSaida.run();
    }
    

    As usual, just call fluxograma() .

    If you do not want the variable:

    private void fluxograma() {
      A();
      (B()? (Runnable) () -> {}: (Runnable) () -> { C(); fluxograma(); }).run();
    }
    

    As usual, just call fluxograma() .

        
    02.11.2017 / 04:47