Sunday, October 22, 2017

HP Prime: BREAK vs. CONTINUE

HP Prime:  BREAK vs. CONTINUE

Introduction

Ever needed to end a loop early?  Find yourself executing a loop where the counter becomes a value that causes an execution error?  An example where this might happen is a loop where a function is divided by the counter variable, and during the loop the counter variable takes the value of 0. 

The HP Prime offers two ways to mitigate potential problems in loops:

1.  You can terminate the loop at that point by using BREAK.

2.  You can skip that loop’s iteration by using CONTINUE.

You can specify how many loop structures are affected by using either the BREAK n or CONTINUE n format. 

A Simple Example

The programs LOOPED1 and LOOPED2 has a FOR structure that divides 10 by every integer from -5 to 5.   (10/-5, 10/-4, etc..)

We can see that the counter will have a problem when the variable reaches 0.  Division by 0 will cause an error and stop execution.  We are going to use BREAK and CONTINUE to mitigate this problem.

LOOPED1 – Break

EXPORT LOOPED1()
BEGIN
// Demonstration: BREAK
LOCAL x,y;
y:={};
// Loop
FOR x FROM −5 TO 5 DO
// Since we can′t
// divide by 0...
IF x==0 THEN
BREAK;
END;
y:=CONCAT(y,{10/x});
END;
RETURN y;
END;

When x=0, the for-loop is stopped.  As a result LOOPED1 returns:
{-2, -2.5, -3.333333333, -5, -10}


LOOPED2 – CONTINUE

EXPORT LOOPED2()
BEGIN
// Demonstration: CONTINUE
LOCAL x,y;
y:={};
// Loop
FOR x FROM −5 TO 5 DO
// Since we can′t
// divide by 0...
IF x==0 THEN
CONTINUE;
END;
y:=CONCAT(y,{10/x});
END;
RETURN y;
END;

In this case when the for-loop encounters x=0, that iteration is skipped and the loop continues.
Result:  {-2, -2.5, -3.333333333, -5, -10, 10, 5, 3.333333333, 2.5, 2}

Eddie


This blog is property of Edward Shore, 2017.