Use conditional statements, program loops and other programming operators to write clear and concise programs.
You can use programs inside or outside solve blocks.
Watch this video to learn more about programming strategies:
Conditional Statements
You can execute or skip certain calculations with conditional statements. Use a conditional statement to direct a program execution along a particular branch.
Example:
Program Loops
A loop is a block of code that causes one or more statements (the body of the loop) to iterate until a termination condition occurs. The following loop types are available:
• for loop—Use a for loop to specify the exact number of iterations for the loop to execute.
• while loop—Use a while loop to stop execution upon the occurrence of a condition.
Example:
Recursion
You can use recursion for evaluating functions in an elegant and concise manner. Consider the following recursion definition for evaluating the greatest common denominator with the help of the mod function:
To write a recursive function, you must name it with a previously undefined name. If you name your recursive function the same name as a PTC Mathcad built-in function or a predefined function, while calculating, your recursive function first looks at the original definition and uses it.
If you define the following:
the second definition of f will be based on the first. Only if you define a function in terms of itself and there is no previous definition, PTC Mathcad treats it recursively.
Recursive function definitions are not always computationally efficient. In some cases, an equivalent iterative loop definition evaluates more quickly.
Exiting Loops and Programs
• The break operator provides a premature exit from a loop.
• The continue operator skips an iteration.
• The return operator exits a program out of the context of a loop.