HP Forums
(49G/50g) Shortest code to increment a variable? - Printable Version

+- HP Forums (https://www.hpmuseum.org/forum)
+-- Forum: HP Software Libraries (/forum-10.html)
+--- Forum: General Software Library (/forum-13.html)
+--- Thread: (49G/50g) Shortest code to increment a variable? (/thread-19835.html)



(49G/50g) Shortest code to increment a variable? - acser - 04-20-2023 11:50 AM

I can think of trivial code like this to increment variable A by one:

A 1 + ‘A’ STO

Are there shorter, faster, more elegant ways to do this?
Thanks,
A


RE: (49G/50g) Shortest code to increment a variable? - Marco Polo - 04-20-2023 12:21 PM

(04-20-2023 11:50 AM)acser Wrote:  I can think of trivial code like this to increment variable A by one:

A 1 + ‘A’ STO

Are there shorter, faster, more elegant ways to do this?
Thanks,
A

1
'A'
STO+

(also available STO- STO* STO/)

or

'A'
INCR

(INCR and DECR increments and decrements by 1 and returns new value)

You can find all commands in menu PRG-->MEM-->ARITH


RE: (49G/50g) Shortest code to increment a variable? - John Keith - 04-20-2023 12:38 PM

Note that all three of these methods are significantly slower than keeping the value represented by A on the stack rather than in a variable. Even if the value is on a higher stack level, e.g. ROT 1. + UNROT is still faster than INCR or STO+. Also use real numbers rather than exact integers if possible.

These optimizations are not important if the incrementing only occurs a few times in the running of the program but they should be considered if the incrementing occurs inside a loop, which it usually does.


RE: (49G/50g) Shortest code to increment a variable? - acser - 04-20-2023 07:11 PM

Thank you all. Very useful.


RE: (49G/50g) Shortest code to increment a variable? - Gil - 04-20-2023 08:45 PM

Note also that STO+
can be used with a variable that contains a list.

Suppose you have done {1 2 3} 'A' STO.
Then try 20 'A' STO+
and press A
to see the new list A {20 1 2 3},
with the number added as the first element of the list A.

Try now with "test" 'A' STO+
and press A
to see the new list A {"test" 20 1 2 3}.

Instead of a string,
you could have a variable name such as 'B':
Try 'B' 'A' STO+
and press A
to see the new list A {B "test" 20 1 2 3}.