samedi 2 décembre 2017

Replace specific elements in an 2d array in C

Im writing a magic square game that replaces random values with X's in a 4x4 matrix. I want the player to be able to replace those X's with numbers.

So far my program only replaces random values with X's and the player is able to input new ones but is also able to replace all of them.

I want to somehow pick out the X's and make the player only replace the X's and keep the old values as they are.

I was thinking about some kind of If() statement before entering the new values to check which ones were replaced by X's but im not sure about how to implement it.

Any help is much appreciated.

My code looks like this so far:

int Array[4][4] = { 0xF,0x4,0x8,0x3,0x1,0xA,0x6,0xD,0x2,0x9,0x5,0xE,0xE,0x7,0xB,0x0 };

int row = 0, col = 0;
int sum = 0, sum2 = 0, sum3 = 0;
srand(time(NULL));
printf("Enter the matrix new values\n\n");
for (int row = 0; row < 4; row++)
{

    for (int col = 0; col < 4; col++)
    {

        if (rand() % 15 < 8)
        {
            printf("%d \t", Array[row][col]); //prints the matrix
        }
        else
        {
            printf("%s \t", "X"); // replaces with X's
        }

    } 

    printf("\n");
}
printf("\n");




for (int i = 0; i < 4; i++)
{
    for (int j = 0; j < 4; j++)
    {
        printf("Enter the %d row %d colum\n", i + 1, j + 1); //enter new values
        scanf_s("%x", &Array[row][col]);
    }
}




printf("Given matrix\n"); //Show the matrix
for (int i = 0; i < 4; i++)
{
    for (int j = 0; j < 4; j++)
    {
        printf("%d\t", Array[row][col]);
    }
    printf("\n");
}
getchar();  

Aucun commentaire:

Enregistrer un commentaire