For starters there is a typo in the program. You omitted the open brace after the loop statement
for (int n=0; n<=5; n++)
^^^^
N = n;
int a[N][N];
//...
There should be
for (int n=0; n<=5; n++) {
^^^^
N = n;
int a[N][N];
//...
Array a
is a variable length array. Its dimension may not be equal to 0. So the variable n
must to start from 1 as it is written in the assignment
for (int n=1; n<=5; n++) {
^^^^
This function call
printMatrix(a, 10, 10);
^^ ^^
does not make sense because the number 10 has nothing common with the array.
And the function declaration
void printMatrix(int **a, int rows, int cols);
^^^^^^^
is invalid. There is a mismatch between the argument type and the parameter type and there is no implicit conversion from one type to another type.
The program can look like
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void printMatrix( size_t rows, size_t cols, int a[][cols] )
{
for ( size_t i = 0; i < rows; i++ )
{
for ( size_t j = 0; j < cols; j++ ) printf( "%3d ", a[i][j] );
printf( "\n" );
}
}
int main( void )
{
const size_t N = 5;
const int UPPER_VALUE = 256;
srand( ( unsigned int )time( NULL ) );
for ( size_t n = 1; n <= N; n++ )
{
int a[n][n];
for ( size_t i = 0; i < n; i++ )
{
for ( size_t j = 0; j < n; j++ ) a[i][j] = rand() % UPPER_VALUE;
}
printf( "Matrix A[%zu][%zu]:\n", n, n );
printMatrix( n, n, a );
printf( "\n" );
}
return 0;
}
Its output might be
Matrix A[1][1]:
117
Matrix A[2][2]:
57 216
50 233
Matrix A[3][3]:
42 117 215
177 218 26
202 81 163
Matrix A[4][4]:
205 178 157 2
229 165 93 94
91 160 39 205
26 242 131 69
Matrix A[5][5]:
147 248 126 107 42
103 149 160 62 70
122 89 17 203 252
222 125 154 224 98
63 61 192 155 222
If the compiler does not support variable length arrays then you have to allocate the arrays dynamically. For example
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void printMatrix( int **a, size_t rows, size_t cols )
{
for ( size_t i = 0; i < rows; i++ )
{
for ( size_t j = 0; j < cols; j++ ) printf( "%3d ", a[i][j] );
printf( "\n" );
}
}
int main( void )
{
const size_t N = 5;
const int UPPER_VALUE = 256;
srand( ( unsigned int )time( NULL ) );
for ( size_t n = 1; n <= N; n++ )
{
int **a = malloc( n * sizeof( int * ) );
for ( size_t i = 0; i < n; i++ )
{
a[i] = malloc( n * sizeof( int ) );
for ( size_t j = 0; j < n; j++ ) a[i][j] = rand() % UPPER_VALUE;
}
printf( "Matrix A[%zu][%zu]:\n", n, n );
printMatrix( a, n, n );
printf( "\n" );
for ( size_t i = 0; i < n; i++ ) free( a[i] );
free( a );
}
return 0;
}