[Math] How to write for / while loop in mathematical notation

functionsnotation

In this question they suggest $$\sum_{i\in S} f(i)$$

I just wanted to clarify if it is okay to notate a while loop like this, where the while loop would be simply looping until some condition is met, executing a function.

b = 10
while (a < b) {
  x()
  a++
}

or even

while (true) {
  x()
  // ...
  if (something) break
}

or wondering if it would also work for a for loop:

for (var i = 0; i < n; i++) {
  x()
}

where none of these functions actually create a sum explicitly, but instead execute a function some number of times.

Best Answer

In pure math, functions don't have "side-effects". Variables are not updated; they are either set to a specific value, or they range over all values simultaneously: there is no "updating", because there is no "time". So, under the strictest possible interpretation, this question doesn't make sense.

To talk about the effects of code purely mathematically, you effectively need to find a way to express it without directly talking about 'time'. The easiest way to do this is to use a recursive definition.

For instance, if x is something like:

if(p(a))
  a = f(a);
else
  a = a+1;

then you might turn that into a sequence, and write:

Let $a_0 =$ [some starting value] . For all natural numbers $n>0$, define $a_n$ as:

$$a_n = \begin{cases}f(a_{n-1}) & \text{if }p(a) \\ a_{n-1} + 1 & \text{otherwise}\end{cases}$$

Then, you can 'access' the value of a after calling x 10 times by just writing $a_{10}$.


...or you can just write some pseudocode, and say "let $a_i$ be the value of a after $i$ iterations of x". As long as you make it clear what you're doing (and as long as your audience knows any programming at all), you should be able to get your point across.