Lesson 15: Matrixes and 2D Arrays


E-mail this post



Remember me (?)



All personal information that you provide here will be governed by the Privacy Policy of Blogger.com. More...



There was a slight pause in my C++ Maniac programming tutorial, due to me answering some of your C & C++ lesson-related questions. You can find some explanations on previous programming materials in my sidebar now, along with other new C & C++ stuff. It seems to me finally, after all troubleshoots are answered (or are they?!), we can bravely continue. This 15th lesson is about matrixes and two-dimensional C++ arrays. Although this one may look significantly more complicated, if you read through it carefully, you will conquer programming matrixes with no problem – I promise you that.




Declaration of a 2D array in C language:

int x[3][2] - matrix 3X2 (3 rows, 2 columns), elements: integers
char myascii[2][4] - array of characters (2 rows & 4 columns)
float sequence[MAXROW][MAXCOL] - MAXROW X MAXCOL matrix




Example of declaration with initialization:

int array[3][3] = {1, 2, 3, 4, 5};
array[0][0] = 1

array[0][1] = 2
array[0][2] = 3
array[1][0] = 4
array[1][1] = 5
array[1][2] = 0 // even though nowhere stated
array[2][0] = 0
array[2][1] = 0
array[2][2] = 0





char cmaniac[7] = {'C', 'M', 'A', 'N', 'I', 'A', 'C'}


/* array of characters */






int y[3][4] = { {1, 2, 3},

{4, 5, 6},
{7, 8, 9} };






y[0][0]= 1 y[0][1]= 2 y[0][2]= 3 y[0][3]= 0

y[1][0]= 4 y[1][1]= 5 y[1][2]= 6 y[1][3]= 0
y[2][0]= 7 y[2][1]= 8 y[2][2]= 9 y[2][3]= 0





Declaration of multidimensional array:

int x[3][2][4] 3D array of integer numbers
float x[3][2][4][1] 4D array of real numbers





Example:

Write your own C program that reads through real matrix, 10x10 dimensioned and finds the smallest element in main diagonal and smallest element in secondary diagonal.



#include <stdio.h>

#define NR_ROW 10

#define NR_COL 10


int main(void) {


int i, j;

float mat[NR_ROW][NR_COL], min_maindg, min_secdg;


printf("Input matrix elements :");
for (i = 0; i < NR_ROW; i++) {
for (j = 0; j < NR_COL; j++) {


printf("\nInput element [%d][%d] : ", i, j);

scanf("%f", &mat[i][j]);


}

}

min_maindg = mat[0][0];


//min el. is mat(0,0), this is why loop starts from 1

for (i = 1; i < NR_ROW; i++) {

if (mat[i][i] < min_maindg) {

min_maindg = mat[i][i];


}

}

min_secdg = mat[0][NR_COL -1];

for (i = 1; i < NR_ROW; i++) {


if (mat[i][NR_COL-i-1] < min_secdg) {


min_secdg = mat[i][NR_COL-i-1];


}

}

printf("\nSmallest el. in main diagonal is: %f",
min_maindg);

printf("\nSmallest el. in second diagonal is: %f",
min_secdg);

}




Shorter version – single run through the matrix:


#include <stdio.h>

#define NR_ROW 10

#define NR_COL 10


int main(void) {


int i, j;

float mat[NR_ROW][NR_COL], min_maindg, min_secdg;

printf("\nInput matrix elements :\n");
for (i = 0; i < NR_ROW; i++) {
for (j = 0; j < NR_COL; j++) {

printf("\nInput element [%d][%d] : ", i, j);

scanf("%f", &mat[i][j]);

if (i == 0 && j == 0) {

min_maindg = mat[i][j];


}

if (i == 0 && j == NR_COL - 1) {

min_secdg = mat[i][j];


}

if (i == j) {
if (mat[i][j] < min_maindg) {

min_maindg = mat[i][j];

}
}
if (i == NR_COL - 1 - j) {
if (mat[i][j] < min_secdg) {

min_secdg = mat[i][j];

}
}
}
}
printf("\nSmallest element in main diagonal is : %f",
min_maindg);

printf("\nSmallest element in second diagonal is : %f",
min_secdg);

}




Example:

Write your own C program that transposes matrix. Program stores given matrix dimensions and every single matrix element must be given. Transposed matrix is the one with rows and columns switched.



#include <stdio.h>

#define MAX_ROW 50

#define MAX_COL 50


int main(void) {

int i, j, m, n, temp;

int mat[MAX_ROW][MAX_COL];



// variable dim is set to smaller value of defined
// maximal number of rows and columns


int dim = (MAX_ROW < MAX_COL)? MAX_ROW : MAX_COL;



// storing matrix size

do {

printf("Input number of rows < %d :", dim);
scanf("%d", &m);
printf("Input number of columns < %d:", dim);
scanf("%d", &n);

} while (m < 1 || m > dim || n < 1 || n > dim);



// storing matrix elements

printf("\nInput of matrix elements :\n");
for (i = 0; i < m; i++) {

for (j = 0; j < n; j++) {


printf("Input element [%d][%d] : ", i, j);

scanf("%d", &mat[i][j]);

}
}



// printing matrix before transposing

printf("\n\nMatrix before transposing:\n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {

printf("%3d", mat[i][j]);


}

printf("\n");
}




// transposing

for ( i=0; i<m; ++i ) {
// looping must start from i+1 !!
for ( j=i+1; j<n; ++j ) {

temp = mat[i][j];

mat[i][j] = mat[j][i];
mat[j][i] = temp;
}
}



// print after transposing
// number of rows becomes number of columns ...

printf("\nMatrix after transposing:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {

printf("%3d", mat[i][j]);

}
printf("\n");
}
} // main





Example of program’s execution:


Input number of rows < 50: 3
Input number of columns < 50: 2

Input of matrix elements :
Input element [0][0] : 1
Input element [0][1] : 2
Input element [1][0] : 3
Input element [1][1] : 4
Input element [2][0] : 5
Input element [2][1] : 6


Matrix before transposing:

1 2
3 4
5 6


Matrix after transposing:

1 3 5
2 4 6





Example:

Write your own C program that stores real matrix whose dimensions are 10x10, and finds the sum of elements from every column and product of elements from every row. Program prints the smallest sum (including parent column’s index), and biggest product (including parent row’s index). Sums and products should be stored in one-dimensional arrays.



#include <stdio.h>

#define NR_ROW 10

#define NR_COL 10


int main(void) {

int i, j;

int min_sum_ind, max_prod_ind;

float mat[NR_ROW][NR_COL];
float sum[NR_COL], prod[NR_ROW];


/*1.variant of input and calculating sums & products*/


for (i = 0; i < NR_ROW; i++) {
for (j = 0; j < NR_COL; j++) {

printf("\nInput element[%d][%d] : ", i, j);

scanf("%f", &mat[i][j]);
}
}

for (j = 0; j < NR_COL; j++) {

sum[j] = 0;

for (i = 0; i < NR_ROW; i++) {

sum[j] += mat[i][j];


}

}

for (i = 0; i < NR_ROW; i++) {

prod[i] = 1;


for (j = 0; j < NR_COL; j++) {


prod[i] *= mat[i][j];

}
}

/*end of input, and sums & products calculation*/



/* finding column’s index for smallest sum */

min_sum_ind = 0;
for (j = 1; j < NR_COL; j++) {
if (sum[j] < sum[min_sum_ind]) {

min_sum_ind = j;

}
}


/* finding row’s index for biggest product */

max_prod_ind = 0;
for (i = 1; i < NR_ROW; i++) {
if (prod[i] > prod[max_prod_ind]) {

max_prod_ind = i;

}
}

printf("\nSmallest sum: %f, parent index: %d\n",
sum[min_sum_ind], min_sum_ind);
printf("\nBiggest product: %f, parent index: %d\n",
prod[max_prod_ind], max_prod_ind);
}




Shorter variant for storing elements and calculating sums & products:

/*2.variant of input and calculating sums & products*/

for (i = 0; i < NR_ROW; i++) {


prod[i] = 1;

for (j = 0; j < NR_COL; j++) {

printf("\nInput element [%d][%d] : ", i, j);

scanf("%f", &mat[i][j]);
prod[i] *= mat[i][j];
if (i == 0) {

sum[j] = 0;


}

sum[j] += mat[i][j];

}
}


/* end of input, and sums & products calculation */






Technorati Tags:
, , , , , ,



5 Responses to “Lesson 15: Matrixes and 2D Arrays”

  1. Anonymous Anonymous 

    Well, Im new to and learning c++, and would just like to comment that you guys are doing a great job. Keep it up.

    (waiting for the next one ^^)

  2. Anonymous Anonymous 

    Thnks,

    It's one man team by the way ;) In your free time advertise "our" site and do your citizen duty! heh

  3. Anonymous Anonymous 

    Complicated.

  4. Anonymous Anonymous 

    Howdy...


    Just one thing. It's matriCes :) Just wanted to let ya know.

  5. Anonymous Anonymous 

    I am new and by looking at the first two examples I jumped ahead in my programing a NXN solver. Thank you.

    Do you have a lesson on how to use procedure with 2D numerical arrays?

Leave a Reply

      Convert to boldConvert to italicConvert to link

 


German Flag Spanish Flag French Flag Italian Flag Portuguese Flag Japanese Flag Korean Flag Chinese Flag British Flag


This Website is optimized for Firefox. Users browsing with Internet Explorer may encounter problems while viewing pages.


C++ Maniac



Learn C



Additional



#include



Learn Converting



Appendix


Links


Previous posts




Daily Lessons for programming in Visual Studio, using C code.