## Iterations and convergence

Hello,
I'm having some problems figuring out how to write a
code that would make an iteration stop after, for
example, there is no more difference between result
from one previous step of iteration and result from
current (last) step of iteration. I only know how
to manually write the number of iterations but I
would like the computer to determine itself how
many are needed and then stop. Here is the example from code:

Code:
```for (iter=0; iter<=40; iter++)
{
for (i=1; i<=2; i++)
for (j=1; j<=2; j++)
g[i][j]=0.25*(p[i][j+1]+p[i][j-1]+p[i+1][j]+p[i-1][j]);
for (i=1; i<=2; i++)
for (j=1; j<=2; j++)
p[i][j]=g[i][j];
}```
Basically, g[i][j] is small example array of 4 x 4
elements and the formula written above takes values
from surroundig elements and updates the g[i][j]
value 40 times. With every iteration there is less
and less difference between last value and the new value.
How would this code above have to be modified so
that this is done automatically, ..I mean - that
you don't have to do "guessing" the number of
iterations and that iterations stop after there
is some minimal difference between last and new value?

thanks,
Tom