1.Creating a matrix
You can declare a matrix in two ways://Static #define ROWS 4 #define COLUMNS 4 int smatrix[ROWS][COLUMNS] //Dynamic int **dmatrix = NULLIf you declare the matrix as dynamic you must allocate it.
2.Assigning values a matrix
You can assign values to the matrix either by using known values or by reading the values from the keyboard.//Assigning with to predefined value
#define VALUE 5
int i,j;
for(i=0;i<ROWS;i++)
{
for(j=0;j<COLUMNS;j++)
{
matrix1[i][j] = VALUE;
}
}
//Reading values from keyboard
int i,j;
puts("Input matrix values: ");
for(i=0;i<ROWS;i++)
{
for(j=0;j<COLUMNS;j++)
{
scanf("%d",&matrix[i][j]);
}
}
Also, the matrix can be fully assigned at creation:int matrix[ROWS][COLUMNS]={ {1,2,3,4}, {3,4,5,6}, {2,3,4,9}, {9, 9, 9, 9}};
3.Outputing to Console
To output a matrix, you must output every element to console. In order to underline the matrix type, you must put an endline after showing each column.#include<stdio.h>
#define ROWS 3
#define COLUMNS 3
int main(void)
{
int matrix[ROWS][COLUMNS] = { {1,2,3}, {1,2,3}, {3,2,1} };
int i,j;
for(i=0;i<ROWS;i++)
{
for(j=0;j<COLUMNS;j++)
{
printf("%d ",matrix[i][j]);
}
putchar('\n');
}
return 0;
}
/*Output
1 2 3
1 2 3
3 2 1
*/
No comments:
Post a Comment
Got a question regarding something in the article? Leave me a comment and I will get back at you as soon as I can!