(49G/50g) Shortest code to increment a variable?
04-20-2023, 11:50 AM
Post: #1
 acser Junior Member Posts: 27 Joined: Sep 2020
(49G/50g) Shortest code to increment a variable?
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
04-20-2023, 12:21 PM
Post: #2
 Marco Polo Member Posts: 278 Joined: Jun 2016
RE: (49G/50g) Shortest code to increment a variable?
(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
04-20-2023, 12:38 PM
Post: #3
 John Keith Senior Member Posts: 1,034 Joined: Dec 2013
RE: (49G/50g) Shortest code to increment a variable?
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.
04-20-2023, 07:11 PM
Post: #4
 acser Junior Member Posts: 27 Joined: Sep 2020
RE: (49G/50g) Shortest code to increment a variable?
Thank you all. Very useful.
04-20-2023, 08:45 PM
Post: #5
 Gil Senior Member Posts: 631 Joined: Oct 2019
RE: (49G/50g) Shortest code to increment a variable?
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}.
 « Next Oldest | Next Newest »

User(s) browsing this thread: