Euro Pe
Euro Pe

Reputation: 73

Translate flowchart to c++ code

I have a problem translating this flowchart below to C++ code.

Flowchart

It should probably look somewhat like this (I know it's wrong for now):

do {
  I1;
  if(!W1) {
      I2;
  ...
  }
}

I1, I2, I3 are instructions. I think I should use boolean variables to do it correctly, but how?

Upvotes: 2

Views: 2625

Answers (4)

Diego
Diego

Reputation: 1

START:
I1();
while(!W1){
    I2();
    while(W2) // or if() it's the same...
        goto START;
    I3();
}
return; // finish

I hope it help

Upvotes: 0

Quentin
Quentin

Reputation: 63114

You are in the case of two crossed loops: neither is nested into the other one, so the usual flow control tools are insufficient.
Many will usually model them with artificial boolean flags, or duplicate part of the code. But this is actually one of the very few (and I do mean very few -- think hard beforehand) use cases of goto.

Ignoring W2's true branch, this looks like a simple while loop:

I1;

while(!W1) {
    I2;

    if(W2)
        /* ? */;

    I3;
}

Now just add the missing branch. The label, of course, should be adequately named to reflect your actual domain logic. Add comments so it's crystal clear, and you're all set.

    // Let's W1 a stuff from our list of stuffs

handleNextStuff:

    // Take a stuff
    I1;

    // Try W1'ing the stuff.
    while(!W1) {
        I2;

        // No way we can W1 this stuff, drop it and try the next one.
        if(W2)
            goto handleNextStuff;

        // A step closer to a W1'd stuff.
        I3;
    }

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 476910

Here's my idea:

for (bool skip_i1 = false; ; skip_i1 = true)
{
    for (bool w2 = true; w2; w2 = W2())
    {
        if (!skip_i1) { I1(); }
        skip_i1 = false;

        if (W1()) { Finish(); return; }

        I2();
    }

    I3();
}

There are two loops in the flow chart, so we have two loops in the code, but because the control flow is "mis-nested", we need a flag (skip_i1) to branch on the overlapping bit. As a variation, you could put skip_i1 = false; into the inner for incrementor, or into an else branch of the if statement.

I assume that the entire code lives in a function of its own (as it better had!), so that we can exit the inner loop directly with return.

Upvotes: 0

hauron
hauron

Reputation: 4668

There is a loop in the flow chart. The condition for stopping the loop is in fact W1.

while (!W1())
{
}

I1 is executed (initially) regardless, and is performed before the loop finish condition check, so let's update the code:

I1();
while (!W1())
{
}

Again, I2 is performed uncoditionally:

I1();
while (!W1())
{              
   I2();
}

Now, W2 affects whether we execute I1 or I3, let's update the code accordingly:

I1();  // for the first, unconditional execution
while (!W1())
{
   I2();
   if (W2())
      I1();
   else
      I3();
}

Upvotes: 5

Related Questions