This is a challenging program asked in one of the campus interviews asked in our college.
Display the matrix elements from the first row, diagonal elements and last row using single loop. The display should contain elements in a z form from the given matrix.
//Program to display Z position elements in a matrix with single loop
#include<stdio.h>
#include<conio.h>
main()
{
int a[10][10];
int i,j;
int m,n;
clrscr();
printf("Enter Row & Column Value \n");
scanf("%d%d",&m,&n);
printf("Enter Matrix Elements\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("\n The given matrix\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%d\t",a[i][j]);
printf("\n");
}
printf("\n The matrix elements in Z position\n");
for(i=0;i<m;i++)
{
printf("\n\n");
for(j=0;j<n;j++)
{
if(i==0) // First Row
printf("%d\t",a[i][j]);
else if(i==m-1) // Last Row
printf("%d\t",a[i][j]);
else if(j==n-(i+1)) // Diagonal Elements
printf("%d\t",a[i][j]);
else
printf("\t");
}
}
getch();
}
OUTPUT
-------
Enter Row & Column Value
3 3
Enter Matrix Elements
1 2 3
4 5 6
7 8 9
The given matrix
1 2 3
4 5 6
7 8 9
The matrix elements in Z position
1 2 3
5
7 8 9
Display the matrix elements from the first row, diagonal elements and last row using single loop. The display should contain elements in a z form from the given matrix.
//Program to display Z position elements in a matrix with single loop
#include<stdio.h>
#include<conio.h>
main()
{
int a[10][10];
int i,j;
int m,n;
clrscr();
printf("Enter Row & Column Value \n");
scanf("%d%d",&m,&n);
printf("Enter Matrix Elements\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("\n The given matrix\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%d\t",a[i][j]);
printf("\n");
}
printf("\n The matrix elements in Z position\n");
for(i=0;i<m;i++)
{
printf("\n\n");
for(j=0;j<n;j++)
{
if(i==0) // First Row
printf("%d\t",a[i][j]);
else if(i==m-1) // Last Row
printf("%d\t",a[i][j]);
else if(j==n-(i+1)) // Diagonal Elements
printf("%d\t",a[i][j]);
else
printf("\t");
}
}
getch();
}
OUTPUT
-------
Enter Row & Column Value
3 3
Enter Matrix Elements
1 2 3
4 5 6
7 8 9
The given matrix
1 2 3
4 5 6
7 8 9
The matrix elements in Z position
1 2 3
5
7 8 9
No comments:
Post a Comment