Square Matrix II

Square Matrix II

topic

Input an integer N and output a two-dimensional array of order N.

Refer to the example for the format of the array.

Input format

The input contains multiple lines, and each line contains an integer N.

When the input line N=0, it means the input is over, and the line does not need to be processed.

Output format

For each input integer N, output a two-dimensional array of order N that meets the requirements.

Each array occupies N rows, and each row contains N integers separated by spaces.

After each array is output, a blank line is output.

data range

0≤N≤100

Input sample

1
2
3
4
5
0

Sample output

1

1 2
2 1

1 2 3
2 1 2
3 2 1

1 2 3 4
2 1 2 3
3 2 1 2
4 3 2 1

1 2 3 4 5
2 1 2 3 4
3 2 1 2 3
4 3 2 1 2
5 4 3 2 1

Algorithm 1:

#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
int n;
int main()
{
    
    
	while(1){
    
    
		cin>>n;
		if(n==0) break;
		for(int i=1;i<=n;i++){
    
    
			for(int j=i;j>1;j--){
    
    
				cout<<j<<" ";
			} 
			for(int j=1;j<=n-i+1;j++){
    
    
				cout<<j<<" ";
			}
			cout<<endl;
		}
		cout<<endl;
	}
	return 0;
 } 

Algorithm 2:

#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
int n;
int N=110;
int main()
{
    
    
	while(1){
    
    
		cin>>n;
		if(n==0) break;
		int a[N][N];
		for(int i=1;i<=n;i++){
    
    
			for(int j=i,k=1;j<=n;j++,k++){
    
    
				a[i][j]=k;
				a[j][i]=k;
			}
		}
		for(int i=1;i<=n;i++){
    
    
			for(int j=1;j<=n;j++){
    
    
				cout<<a[i][j]<<" ";
			}
			cout<<endl;
		}
	}
	return 0;
 } 

Algorithm three:

#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
int n;
int main()
{
    
    
	while(1){
    
    
		cin>>n;
		if(n==0) break;
		for(int i=1;i<=n;i++){
    
    
			for(int j=1;j<=n;j++){
    
    
				cout<<abs(i-j)+1<<" ";
			}
			cout<<endl;
		}
		cout<<endl;
	}
	return 0;
 } 

Guess you like

Origin blog.csdn.net/qq_52354698/article/details/112970290