How to for loop in Math like C?

295 Views Asked by At

In C, we can for loop easily. But I don't know how we can loop in Math like C.

For example, I want to loop in Math like this C code:

int i;
int a = 10;
for (i = 1; i < 100; i++)
{
    a -= 2;
}
2

There are 2 best solutions below

2
On BEST ANSWER

In general, we don't need to loop in mathematics, because we have alternative constructs.

Two examples, the first one is probably the best translation of yours:

$u_0 = 10, u_{n+1} = u_n - 2$, an arithmetic sequence, of which you're asking the 99-th value ($u_{99}$).

But often, you'll want to have an operation like the functional programming "fold/reduce"; which acts like a for-loop over an array, for a given operator.

For this, we have the "indexed $n$-ary operators", also called "generalized operators".

For addition: $$\sum_{i=1}^{i=n} a^i = a^1 + a^2 + \dots + a^n$$

For multiplication:

$$\prod_{i=0}^{i=n} i+4 = 4 \times 5 \times \dots \times (n + 4)$$

You can also define an $n$-ary version for basically every binary operator you can find: $\bigcup$, $\bigcap$, etc.

The rest of the syntax consists in picking your indices intelligently. Say you wanted to sum over all elements of a matrix (generally done with a nested for-loop with $i$ and $j$ iterators), you could define it as something like this:

$$\sum_{i=1, j=1}^{i=n, j=m} a_{ij}$$

0
On

Let $a_i$ be the value of the variable a after the $i$-iteration, then $$a_0 = 10, \qquad a_{i+1} = a_i - 2$$

One could show by induction that $$a_i = 10-2i$$ for all $i\in\mathbb{N}$.