Content of the lesson:
A 2D array uses another dimension compared to a standard array. You can see an illustration of an empty 2D array (5x5):
A perfect analogy is a list of squared paper with dimensions m x n squares.
Take a look at writing an empty 2D array to screen:
#include "stdafx.h"
#define M 2
#define N 4
int _tmain(int argc, _TCHAR* argv[])
{
int p[M][N];
int radek, sloupec;
for (radek = 0; radek < M; radek++)
{
for (sloupec = 0; sloupec < N; sloupec++)
{
p[radek][sloupec] = 0;
}
}
for (radek = 0; radek < M; radek++)
{
for (sloupec = 0; sloupec < N; sloupec++)
{
printf("%d ", p[radek][sloupec]);
}
}
fflush(stdin);
getchar();
return 0;
}
Numbers are written all together and you absolutely cannot see that this is a 2D array. To illustrate this fact you have to use another writeln command after writing every line to console.
#include "stdafx.h"
#define M 2
#define N 4
int _tmain(int argc, _TCHAR* argv[])
{
int p[M][N];
int radek, sloupec;
for (radek = 0; radek < M; radek++)
{
for (sloupec = 0; sloupec < N; sloupec++)
{
p[radek][sloupec] = 0;
}
}
for (radek = 0; radek < M; radek++)
{
for (sloupec = 0; sloupec < N; sloupec++)
{
printf("%d ", p[radek][sloupec]);
}
printf("\n");
}
fflush(stdin);
getchar();
return 0;
}
In the following examples we will try to fill a square 2D array (dimensions set to nxn) with numbers. To be able to write it to screen, choose the dimensions to 10x10 items.
#include "stdafx.h"
#define M 10
#define N 10
int _tmain(int argc, _TCHAR* argv[])
{
int p[M][N];
int radek, sloupec;
for (radek = 0; radek < M; radek++)
{
for (sloupec = 0; sloupec < N; sloupec++)
{
}
}
for (radek = 0; radek < M; radek++)
{
for (sloupec = 0; sloupec < N; sloupec++)
{
printf("%d ", p[radek][sloupec]);
}
printf("\n");
}
fflush(stdin);
getchar();
return 0;
}
1 | 1 | 1 |
1 | 1 | 1 |
1 | 1 | 1 |
p[radek, sloupec]=1;
1 | 2 | 3 |
1 | 2 | 3 |
1 | 2 | 3 |
p[radek, sloupec]=sloupec;
1 | 1 | 1 |
2 | 2 | 2 |
3 | 3 | 3 |
p[radek][sloupec]=radek;
1 | 2 | 3 |
2 | 4 | 6 |
3 | 6 | 9 |
p[radek][sloupec]=radek*sloupec;
1 | 0 | 0 |
0 | 1 | 0 |
0 | 0 | 1 |
if (radek==sloupec)
{
p[radek, sloupec]=1;
}
else
{
p[radek, sloupec]=0;
}
1 | 1 | 1 |
0 | 1 | 1 |
0 | 0 | 1 |
if (radek<=sloupec)
{
p[radek, sloupec]=1;
}
else
{
p[radek, sloupec]=0;
}
1 | 0 | 1 |
0 | 1 | 0 |
1 | 0 | 1 |
if ((radek=sloupec) || (radek=M-sloupec+1))
{
p[radek][sloupec]=1;
}
else
{
p[radek][sloupec]=0;
}
Write a program to compute the arithmetic mean of all inserted values inside a 2D array.
Write a program to find out the minimum and the maximum values from all inserted values in a 2D array.