We know that invariant is expression, that true before, in each iteration, and after the loop. So we should find out all invariants of the following code of spiral traversal of the square matrix, beginning from its center.
Loop to explore:
int iInd = N / 2;
int jInd = N / 2;
int iStep = 1;
int jStep = 1;
printf("%d ", A[iInd][jInd]);
for (int i = 0; i < N; i++) {
for (int h = 0; h < i; h++)
printf("%d ", A[iInd][jInd += jStep]);
for (int v = 0; v < i; v++)
printf("%d ", A[iInd += iStep][jInd]);
jStep = -jStep;
iStep = -iStep;
}
for (int h = 0; h < N - 1; h++)
printf("%d ", A[iInd][jInd += jStep]);
The whole C++
program:
#include <stdio.h>
#define N 13
void main() {
int A[N][N];
for (int i = 0; i<N; i++)
for (int j = 0; j<N; j++)
A[i][j] = i * 13 + j; //simple filling of matrix
int iInd = N / 2;
int jInd = N / 2;
int iStep = 1;
int jStep = 1;
printf("%d ", A[iInd][jInd]); //the starting of spiral printing
for (int i = 0; i < N; i++) {
for (int h = 0; h < i; h++)
printf("%d ", A[iInd][jInd += jStep]);
for (int v = 0; v < i; v++)
printf("%d ", A[iInd += iStep][jInd]);
jStep = -jStep;
iStep = -iStep;
}
for (int h = 0; h < N - 1; h++)
printf("%d ", A[iInd][jInd += jStep]);
//the ending of spiral printing
}
Output of the program and internal structure: image here
I showed my ideas to teacher - invariants are:
- i < N+1
- h < N
- v < N
Teacher told me that it is not invariants. It should be expression, contains iInd
and jInd
.