[Functions]D. Liang 5.17 Displaying matrix of 0s and 1s.c

Description

Write a function that displays an n by n matrix. Each element in the matrix is 0 or 1. The elements of first row, the elements of the first column and the diagonal elements are 1s, the other are 0s.

Input

The first line is a positive integer (1 <= t <= 10), denoting the number of test cases followed.
In each test case, the input is one single line, containing a positive integer n (1 <= n <= 100) which denotes the width of matrix.

Output

For each test case, the output contains n line and each line consists of n integers separated by white spaces.
(There is a white spaces in front of the first integer in each line, no white spaces behind the last integer in each line.)

Sample Input

4
1
2
3
10

Sample Output

 1
 1 1
 1 1
 1 1 1
 1 1 0
 1 0 1
 1 1 1 1 1 1 1 1 1 1
 1 1 0 0 0 0 0 0 0 0
 1 0 1 0 0 0 0 0 0 0
 1 0 0 1 0 0 0 0 0 0
 1 0 0 0 1 0 0 0 0 0
 1 0 0 0 0 1 0 0 0 0
 1 0 0 0 0 0 1 0 0 0
 1 0 0 0 0 0 0 1 0 0
 1 0 0 0 0 0 0 0 1 0
 1 0 0 0 0 0 0 0 0 1

Analysis:

***According to the observation matrix, there are the following rules:

  1. All elements in the first row are 1;
  2. All elements in the first column are 1;
  3. All diagonal elements are 1;
  4. All other elements are 0 except the above situations;
  5. Branches i i and columns j j to discuss.

My code

//   Date:2020/4/3
//   Author:xiezhg5
#include <stdio.h>
int main(void)
{
	int m;
	scanf("%d",&m);
	while(m--)      //判断条件可还行 
	{
		int n,i,j;
		scanf("%d",&n);      //表明用户将要输入n个数 
        for(i=0;i<n;i++)    //i表示行 
        {
        	for(j=0;j<n;j++)  //嵌套for循环,j表示列 
        	{
        		if(i==j||i==0||j==0)   //矩阵规律 
        			printf(" 1");     //注意数字间要留空格 
        		else
        			printf(" 0");
            }
            printf("\n");
        }
	}
	return 0;
}
发布了165 篇原创文章 · 获赞 124 · 访问量 5614

猜你喜欢

转载自blog.csdn.net/qq_45645641/article/details/105290183
今日推荐