How to print a two-dimensional array with a for loop?
Two-dimensional arrays are stored by row by default in the memory, such as a two-dimensional array {, 3 ,}, {, 6 }}, in the memory, the storage sequence is 1, 2, 3, 4, 5, and 6. That is to say, if these six array elements are numbered from 0 to 5, from their numbers, we can introduce their row numbers and column numbers in a two-dimensional array. For example, a row number is an integer operator of the serial number to the number of columns, and a column number is the remainder of the serial number to the number of columns. So let alone a two-dimensional array. Other dimension Arrays can also be printed using a for loop.
The Code is as follows:
| 123456789101112131415161718192021222324 |
// 1312.cpp: defines the entry point of the console application.// #include "stdafx.h"#include <stdio.h>#define MAXX 2#define MAXY 3void printArray(){ int array[MAXX][MAXY] = { 1, 2, 3, 4, 5, 6 }; for (int i = 0; i < MAXX*MAXY; i++) { int x = i / MAXY; int y = i%MAXY; printf("The row number is % d, and the column number is % d \ n", x, y); printf("%d\n", array[x][y]); }}int main(){ printArray(); getchar(); return 0;} |
Effect