Pergunta

Is it possible to write this flowchart into C++ without variables and goto?

Flowchart

That's what I already have:

i1;
i2;
if(w1) {
    i3;
    while(w2) {
        i2;
        if(w1) { break; } // and it shouldn't do i4;
        i3;
    }
    i4;
}
i5;
Foi útil?

Solução

You can do it with some simple recursion. You have to be careful that your recursion has an appropriate "stop" condition to avoid a stack overflow.

Naming each "box" as a function, we get basically the following:

#include <iostream>
using namespace std;

void start_flowing();

int main()
{
   // This is the topmost "box"
   start_flowing();
   return 0;
}

void action_0();  // first "action" box
void check_0();   // first "decision" box
void action_1();  // second "action" box
void check_1();   // second "decision" box
void action_2();  // third "action" box
void complete();  // final "action" box

void start_flowing()
{
   // first box goes to second box directly
   action_0();
}

void action_0()
{
   // first action box goes to first decision directly
   check_0();
}

void check_0()
{
   // whatever this means...
   // this does the evaluation of the decision
   bool result = do_the_check();

   if(result)
   {
      // continue "down" to next action box
      action_1();
   }
   else
   {
      // short circuit out to completion
      complete();
   }
}

void action_1()
{
   check_1();
}

void check_1()
{
   // whatever this means...
   // this does the evaluation of the decision
   bool result = do_the_check();

   if(result)
   {
      // continue "down" to next action box
      action_2();
   }
   else
   {
      // jump back "up" to first action box
      action_0();
   }
}

void action_2()
{
   // completes the sequence
   complete();
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top