#include <stdio.h> #include <stdlib.h> /* Puzzle D05 -- fill an array with integers in ascending order */ #define COLS 7 #define ROWS 5 void print2DArray ( int nrows, int ncols, int x[nrows][ncols] ) { int r, c; for ( r=0; r<nrows; r++ ) { for ( c=0; c<ncols; c++ ) printf("%3d,", x[r][c] ); printf("\n"); } } void fill2DArray ( int nrows, int ncols, int x[nrows][ncols] ) { int r, c, val = 0; for ( r=0; r<nrows; r++ ) { for ( c=0; c<ncols; c++ ) x[r][c] = val++ ; } } int main() { int x[ROWS][COLS] ; /* Fill the array with ascending integers */ fill2DArray( ROWS, COLS, x ); /* Print the array using our function */ print2DArray( ROWS, COLS, x ); printf("\n"); return 0; }
Here is a more convenient version (which may not compile on all compilers). Delete the pre-processor constants if you use this version.
int main() { int ROWS, COLS; printf("rows: "); scanf("%d", &ROWS); printf("cols: "); scanf("%d", &COLS); int x[ROWS][COLS] ; /* Fill the array with ascending integers */ fill2DArray( ROWS, COLS, x ); /* Print the array using our function */ print2DArray( ROWS, COLS, x ); printf("\n"); return 0; }