Upper Triangle C Language

upper triangle

Time Limit:  1 Sec   Memory Limit:  128 MB

Topic description

Above the main diagonal of a square matrix is ​​called the "upper triangle".

Please design a program for filling the upper triangular region of a square matrix of order n. The filling rule is: use the natural number sequence of 1, 2, 3…., starting from the upper left corner, and filling in a clockwise direction.


For example: when n=3, output:

1 2 3

6 4

5

When n=4, the output:

1  2 3 4

9 10 5

8  6

7

enter

an N

N(1<N<20)

output

Upper triangular elements with a space after each number

sample input

4

Sample output

1 2 3 4
9 10 5
8 6
7

hint

#include <stdio.h>
#include <stdlib.h>
intmain()
{
    int n,a[100][100]={0},x=0,y=0,z=1;
    scanf("%d",&n);
    a[x][y]=1;
    while (z<n*(n+1)/2)
    {
        // go right
        while(y+1<n&&!a[x][y+1])
        {
            a[x][++y]=++z;
        }
 
        // slope down
        while(x+1<n&&y-1>=0&&!a[x+1][y-1])
        {
            a[++x][--y]=++z;
        }
 
        //up
        while(x-1>=0&&!a[x-1][y])
        {
            a[--x][y]=++z;
        }
 
    }
    // output
    for(x=0;x<n;x++)
    {
        for(y=0;y<n-x;y++)
        {
            printf("%d ",a[x][y]);
        }
        printf("\n");
    }
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324735212&siteId=291194637