Monday, October 31, 2011

The Primary and Secondary Diagonal of a Matrix in ANSI C

Let's consider a matrix with 4 rows and 4 columns:
The primary diagonal is formed by the elements a00, a11, a22, a33 (red). The row-column condition is row=column.

The secondary diagonal is formed by the elements a03, a12, a21, 30 (blue). The row-column condition is row=numberOfRows - column -1.

We shall define and implement two functions: one for printing the primary diagonal and one for printing the secondary diagonal:
/*
 * Description:
 *  Prints the primary diagonal of a square matrix
 * Parameters:
 *  mat - a pointer to the the matrix
 *  rows - the number of rows
 *  columns - the number of columns
 * Returns:
 *  Nothing
 */
void PrintPrimaryDiagonal(int mat[][COLUMNS], int rows, int columns)
{
   int i;
   /*Checks if the matrix is square*/
   if(rows==columns)
   {
      /*Prints only the elements who are on the primary diagonal*/
      for(i=0; i<rows; i++)
      {
         printf("%d ",mat[i][i]);
      }
   }
   else
   {
      puts("Matrix is not square");
   }
}
/*
 * Description:
 *  Prints the secondary diagonal of a square matrix
 * Parameters:
 *  mat - a pointer to the the matrix
 *  rows - the number of rows
 *  columns - the number of columns
 * Returns:
 *  Nothing
 */
void PrintSecondaryDiagonal(int mat[][COLUMNS], int rows, int columns)
{
   int i;
   /*Checks if the matrix is square*/
   if(rows==columns)
   {
      /*Prints only the elements who are on the secondary diagonal*/
      for(i=0; i<columns; i++)
      {
         printf("%d ",mat[i][rows-i-1]);
      }
   }
   else
   {
      puts("Matrix is not square");
   }
}
Here's an example on how to use this functions:
#include<stdio.h>

#define ROWS 4
#define COLUMNS 4

void PrintPrimaryDiagonal(int mat[][COLUMNS], int rows, int columns);
void PrintSecondaryDiagonal(int mat[][COLUMNS], int rows, int columns);

int main(void)
{
   int matrix[ROWS][COLUMNS] = { {1,2,3,4}, {4,5,6,8}, {9,7,2,1}, {3,2,5,9} };
   puts("The primary diagonal is: ");
   PrintPrimaryDiagonal(matrix, ROWS,COLUMNS);
   puts("\nThe secondary diagonal is: ");
   PrintSecondaryDiagonal(matrix,ROWS,COLUMNS);
   return 0;
}
/*Output
The primary diagonal is:
1 5 2 9
The secondary diagonal is:
4 6 7 3
 */

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