lundi 3 janvier 2022

C program to fill an n x n matrix in a spiral form

I am implementing a C program using functions to fill a square matrix in a spiral form. Here is what I already did:

#include <stdio.h>
#include <conio.h>

const N = 5;
int top = 0;
int bottom = N - 1;
int right = 0;
int left = N -1;

int main(){
    int z = 1 /*N = 5*/;
    int Array[100][100];
    while (z <= (N*N))
    {
        FillRowForward(Array, z);
        FillColumnDownward(Array, z);
        FillRowBackward(Array, z);
        FillColumnUpward(Array, z);
    }

    printf("Two dimensional array elements: \n");

    for (int i = 0; i < N; i++)
    {
        // printf("\t");
        for (int j = 0; j < N; j++)
        {
            printf("%d \t", Array[i][j]);
        }
        printf("\n");
    }

    return 0;
}


/*Definition of functions*/

int FillRowForward(int A[][N], /*int top, int left, int right,*/ int Z)
{
    for (int i = right; i <= left; i++)
    {
        A[top][i] = Z++;
    }
}

int FillColumnDownward(int A[][N], /*int top, int bottom, int right,*/ int Z)
{
    for (int j = top + 1; j <= bottom; j++)
    {
        A[j][bottom] = Z++;
    }
}

int FillRowBackward(int A[][N], /*int bottom, int left, int right,*/ int Z)
{
    for (int i = left - 1; i >= top; i--)
    {
        A[bottom][i] = Z++;
    }
}

int FillColumnUpward(int A[][N], /*int top, int bottom, int right,*/ int Z)
{
    for (int j = bottom - 1; j >= top + 1; j--)
    {
        A[j][left] = Z++;
    }

}

The first function is supposed to fill the first row (FillRowForward), the next is supposed to fill the first column downward and so on until all the matrix is filled. But when I run it only shows a black and blank screen. No output. Need some help on this please!

Aucun commentaire:

Enregistrer un commentaire