Tuesday, August 14, 2012

Reverse Diagonal Elements of a Square Matrix using C language

Genaerally 3x3 matrix is represented as
| a1 a2 a3|
| a4 a5 a6|
| a7 a8 a9|
We need reverse diagonal elements means a3,a5,a7. Now observe the indices of these elements they are (0,2),(1,1),(2,0). By observing the indices we can say that by adding the row and column indes we are getting the one less than the size of matrix. means if the matrix size is 4x4 then the sum of reverse diagonal indeces is 4-1=3. based on this logic program is written. The matrix can be represented by the two dimensional array so we need two dimensional array. to load and manipulate this array we need two for loops. one for loop deals with the row and second for loop deals with the columns.
This program takes the size of square matrix as the input and according to it the elements of the matrix are loaded into the 2Darray.
I will deal the For loop indetail after.
Progrm:
#include<conio.h>
#include<stdio.h>
void main()
{
int i,j,a[20][20],k=1,n;
printf("\n Enter the size of square matrix");
scanf("%d",&n);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
a[i][j]=k;
k++;
}
}
printf("\n Reverse Diagonal elements:");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(i+j==n-1)
{
printf("\n %d",a[i][j]);
}
}
}
getch();
}

 

No comments:

Post a Comment

DC motor control with Pulse Width Modulation Part 1

DC Motor intro DC motor is a device which converts electrical energy into kinetic energy. It converts the DC power into movement. The typica...