If Else in Modelica

Branching with if and else in Modelica is straightforward.

model IfElseExample
  function print
    input String str;
  external "C" print(str) annotation(Include="#include <stdio.h>");
  end print;

equation
  // Here's a basic example.
  if 7 mod 2 == 0 then
    print("7 is even");
  else
    print("7 is odd");
  end if;

  // You can have an `if` statement without an else.
  if 8 mod 4 == 0 then
    print("8 is divisible by 4");
  end if;

  // Logical operators like `and` and `or` are often useful in conditions.
  if 8 mod 2 == 0 or 7 mod 2 == 0 then
    print("either 8 or 7 are even");
  end if;

  // A variable can be declared before conditionals; it will be available in the current
  // and all subsequent branches.
  protected
    Integer num = 9;
  equation
    if num < 0 then
      print(String(num) + " is negative");
    elseif num < 10 then
      print(String(num) + " has 1 digit");
    else
      print(String(num) + " has multiple digits");
    end if;
end IfElseExample;

Note that in Modelica, you don’t need parentheses around conditions, but the then keyword is required after the condition. The end if is also required to close the if statement.

To run this Modelica model, you would typically use a Modelica simulation environment. The output would be similar to:

7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit

Modelica doesn’t have a direct equivalent to the ternary operator found in some other languages, so you’ll need to use a full if statement even for basic conditions.

It’s important to note that Modelica is primarily used for modeling and simulation of physical systems, so the way conditionals are used might differ from procedural programming languages. In Modelica, equations are solved simultaneously rather than executed sequentially.