141_MATRIX_141
141_MATRIX_141

Reputation: 13

Filling a two-dimensional array correctly

I'm stuck in place. I cannot come up with the algorithm and will fill up the square matrix as below:

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

Upvotes: 1

Views: 110

Answers (2)

manoliar
manoliar

Reputation: 182

This is what you want. You do not need to use if statement.

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

Upvotes: 2

Be Ta
Be Ta

Reputation: 45

i think this would work for just above the main diagonal..

   #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:

Upvotes: 0

Related Questions