Main Content

Do While Loop

This example shows how to implement a do while loop construct by using Simulink® blocks and Stateflow® Charts.

C Construct

num_iter = 1;
do {
   flag = func();
   num_iter++;
   }
while (flag && num_iter <= 100)

Modeling Pattern for Do While Loop: While Iterator Subsystem block

One method for creating a do while loop is to use a While Iterator Subsystem block from the Simulink > Ports & Subsystems library.

1. Open example model ex_do_while_loop_SL.

The model contains a While Iterator Subsystem block that repeats execution of the contents of the subsystem during a simulation time step.

Observe the following settings in the While Iterator Subsystem:

  • The func subsystem block has an output flag of 0 or 1 depending on the result of the algorithm in func( ). func() is the Function name in func subsystem.

  • For the While Iterator block, the Maximum number of iterations is 100.

  • For the While Iterator block, the While loop type is do-while.

2. To build the model and generate code, press Ctrl+B.

The code implementing the do while loop is in the ex_do_while_loop_SL_step function in ex_do_while_loop_SL.c:

/* Model step function */
void ex_do_while_loop_SL_step(void)
{
  int32_T s1_iter;

  /* Outputs for Iterator SubSystem: '<Root>/While Iterator Subsystem' incorporates:
   *  WhileIterator: '<S1>/While Iterator'
   */
  s1_iter = 1;

  /* SystemReset for Atomic SubSystem: '<S1>/func' */
  func_Reset();

  /* End of SystemReset for SubSystem: '<S1>/func' */
  /* End of Outputs for SubSystem: '<Root>/While Iterator Subsystem' */
  do {
    func();
    s1_iter++;
  } while (flag && (s1_iter <= 100));
}

Modeling Pattern for Do While Loop: Stateflow Chart

1. Open example model ex_do_while_loop_SF.

In the model, the ex_do_while_loop_SF/Chart executes the do while loop.

The chart contains a While loop decision pattern that you add by selecting Chart > Add Pattern in Chart > Loop > While.

2. To build the model and generate code, press Ctrl+B.

The code implementing the do while loop is in the ex_do_while_loop_SF_step function in ex_do_while_loop_SF.c:

/* Model step function */
void ex_do_while_loop_SF_step(void)
{
  int32_T num_iter;

  /* Chart: '<Root>/Chart' */
  num_iter = 1;
  do {
    func();
    num_iter++;
  } while (flag && (num_iter <= 100));
}

See Also

Related Topics