PROBLEM 12:
Write a C Program that uses nested loops to produce a N x N (square) matrix A with 0's in the diagonal, 1's in the entries just above and below the diagonal element, 2's above and below that, and so on. The 5 x 5 matrix should look like this:
0 1 2 3 4
1 0 1 2 3
2 1 0 1 2
3 2 1 0 1
4 3 2 1 0
CODE:
#include<stdio.h>
int main()
{
int i=0,j=0;
for(i=0;i<5;i++)
{
printf("%d ",i);
for(j=1;j<=4;j++)
{
if(i==1&&j==1)
{
j=j-1;
printf("%d ",j);
j=j+1;
}
else if(i==1&&j==2)
{
j=j-1;
printf("%d ",j);
j=j+1;
}
else if(i==1&&j==3)
{
j=j-1;
printf("%d ",j);
j=j+1;
}
else if(i==1&&j==4)
{
j=j-1;
printf("%d ",j);
j=j+1;
}
else if(i==2&&j==1)
{
printf("%d ",j);
}
else if(i==2&&j==2)
{
j=j-2;
printf("%d ",j);
j=j+2;
}
else if(i==2&&j==3)
{
j=j-2;
printf("%d ",j);
j=j+2;
}
else if(i==2&&j==4)
{
j=j-2;
printf("%d ",j);
j=j+2;
}
else if(i==3&&j==1)
{
j=j+1;
printf("%d ",j);
j=j-1;
}
else if(i==3&&j==2)
{
j=j-1;
printf("%d ",j);
j=j+1;
}
else if(i==3&&j==3)
{
j=j-3;
printf("%d ",j);
j=j+3;
}
else if(i==3&&j==4)
{
j=j-3;
printf("%d ",j);
j=j+3;
}
else if(i==4&&j==1)
{
j=j+2;
printf("%d ",j);
j=j-2;
}
else if(i==4&&j==2)
{
printf("%d ",j);
}
else if(i==4&&j==3)
{
j=j-2;
printf("%d ",j);
j=j+2;
}
else if(i==4&&j==4)
{
j=j-4;
printf("%d ",j);
j=j+4;
}
else
printf("%d ",j);
}
printf("\n");
}
return 0;
}
Program Output:
For more problems click here
No comments:
Post a Comment