Tuesday, October 18, 2011

How to Create, Assign Values to and Output a Matrix in C

In the examples bellow, we shall consider int matrices in order to simplify the operations.

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 = NULL
If 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!

Related Posts Plugin for WordPress, Blogger...
Recommended Post Slide Out For Blogger