1

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:

  1. i < N+1
  2. h < N
  3. v < N

Teacher told me that it is not invariants. It should be expression, contains iInd and jInd.

D7ILeucoH
  • 97
  • 9
  • All three of your statements are invariants of the corresponding loops, but so is e.g. `1 + 1 == 2` an invariant. The more relevant question is what the *useful* invariants are for proving the correctness of the code. Without a statement of what needs to be proved about this code, there is no motivation to find any invariants. – kaya3 Nov 21 '19 at 19:34

0 Answers0