c - 正确填充二维数组

标签 c arrays

我被困在原地。我想不出算法,将按如下方式填充方阵:

https://ibb.co/JcpX6SH

"Gets a natural number n from the user n not more than 20. Fills in a square table as below. The numbers below the main diagonal (a21; a31; a32, etc.) are given by the user."

#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;
}

最佳答案

这就是你想要的。 您不需要使用 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;
}

关于c - 正确填充二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54051788/

相关文章:

c - 为什么这个 atof() 对于非 0.0 字符串数字返回 0.0?

c - 数学函数在现代处理器上需要多少周期

c - -1 不小于 12?

c - 如何开始编辑 pidgin 源代码?

c - 如何在C中的结构中打印字符串

iphone - 获取路由器范围内设备的MAC地址

java - 如何将字符串放入二维数组中

c - 在 GDB 中,您可以将内存设置为 char 数组吗?

python - 成对平方差的高效 Numpy 计算

javascript - 如何访问和处理嵌套对象,数组或JSON?