Matrix Printing In C
This section will deal to enhance understanding matrix printing using loops and conditional statements. We shall print various matrices to learn how loops in C works.
Simple 3x3 Matrix Printing
#include <stdio.h>
int main()
{
int i,j;
for(i = 1; i <= 3; i++)
{
for(j = 1; j <= 3; j++)
printf("1 ");
printf("\n");
}
return 0;
}
The output should look like this −
1 1 1 1 1 1 1 1 1
Zero Matrix Printing
#include <stdio.h>
int main()
{
int i,j;
for(i = 1; i <= 3; i++)
{
for(j = 1; j <= 3; j++)
printf("0 ");
printf("\n");
}
return 0;
}
The output should look like this −
0 0 0 0 0 0 0 0 0
Unit Matrix Printing
#include <stdio.h>
int main()
{
int i,j;
for(i = 1; i <= 3; i++)
{
for(j = 1; j <= 3; j++)
{
if(i == j)
printf("1 ");
else
printf("0 ");
}
printf("\n");
}
return 0;
}
The output should look like this −
1 0 0 0 1 0 0 0 1
Reverse Diagonal Matrix
#include <stdio.h>
int main()
{
int i,j;
for(i=1;i
The output should look like this −
0 0 1
0 1 0
1 0 0
Advertisements