正确填充二维数组

时间:2019-01-05 12:01:14

标签: c arrays

我被卡在适当的位置。我无法提出算法,因此将填充方阵,如下所示:

https://ibb.co/JcpX6SH

  

“从用户n中获得不超过20的自然数n。如下所示填写方表。主对角线以下的数字(a21; a31; a32等)由用户给出。” < / p>

#include <stdio.h>

int main() {
	
	int tab[20][20] = { {0},{0} };
	int size = 0;
	printf("Enter the natural number n not more than 20: ");
	while (scanf_s("%d", &size) != 1 || size < 0 || size >20 || getchar() != '\n')
	{
		while (getchar() != '\n');
		printf("Error. Correct!");
	}

	for (int x = 0; x < size; x++)
	{
		for (int y = 0; y < size; y++)
		{
			if (y==x)
			{
				tab[x][y]=1; // what's next?
			}
		}
	}

	for (int x = 0; x < size; x++)
	{
		for (int y = 0; y < size; y++)
		{
			printf("%d ",tab[x][y]);
		}
		printf("\n");
	}

	return 0;
}

2 个答案:

答案 0 :(得分:2)

这就是您想要的。 您无需使用if语句。

#include <stdio.h>

int main()
{

    int tab[20][20]={ {0},{0} };
    int size = 6,n=0;



    for (int x = 0; x < size; x++)
    {
        n=0;
        for (int y = x; y < size; y++)
        {
            n++;
            tab[x][y]=n; //fill the upper part of the matrix including diagonal
        }
    }
    for (int x = 1; x < size; x++)
    {

        for (int y = 0; y < x; y++)
        {

            tab[x][y]=8; //fill the lower part of the matrix
            //or ask for user input
        }
    }

    for (int x = 0; x < size; x++)
    {
        for (int y = 0; y < size; y++)
        {
            printf("%d ",tab[x][y]);
        }
        printf("\n");
    }

    return 0;
}

答案 1 :(得分:0)

我认为这将在主对角线上方工作。

   #include <stdio.h>

    int main() {

        int tab[20][20] = { {0},{0} };
        int size = 0;
        printf("Enter the natural number n not more than 20: ");
        while (scanf("%d", &size) != 1 || size < 0 || size >20 || getchar() != '\n')
        {
            while (getchar() != '\n');
            printf("Error. Correct!");
        }

        for (int x = 0; x < size; x++)
        {
            printf("%d. diagonal value:", x+1);
            scanf("%d", & tab[0][x]);

        }
        for (int x = 0; x < size; x++)
        {

            for (int y = x; y < size; y++)
            {
                if (y==x)
                {
                    tab[x][y]=1; // what's next?
                }
                else if(x>0){
                    tab[x][y]=tab[x-1][y-1];

                }

            }
        }

        for (int x = 0; x < size; x++)
        {
            for (int y = 0; y < size; y++)
            {
                printf("%d ",tab[x][y]);
            }
            printf("\n");
        }

        return 0;
    }

output:

相关问题