Search code examples
c++flowchartcontrol-structure

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?


Solution

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