-1
int a[3][4], i, j;
int row_total;
printf("Enter matrix values : \n");
for (i = 1; i <= 3; i++) {
    for (j = 1; j <= 4; j++)
        scanf("%d", &a[i][j]);
}
row_total *= a[i][j];
if (row_total > 0) {
    printf("%d\n", row_total);
}

The matrix in the example has 3 rows and 4 columns. The values of this matrix are determined by the user. There are examples everywhere in the form of the product of 2 matrices. But I couldn't find how to process the values in rows of a single matrix. I need to multiply the values that the user enters for the row. How can I find the product of the values written in the rows of the matrix?

In the last part, I just tried to print the values to see if I could read the matrix multiplication of the code. But I could not read the values and get any multiplication result.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
ckot
  • 263
  • 1
  • 11
  • 2
    "*how to process the values in rows*". Just iterate along the row. For example, to iterate over row `r` do `for (int col = 0; col < 4; col++) printf("Row %d column %d = %d\n", r, col, a[r][col]);` – kaylum Jan 11 '22 at 22:07
  • Please note that, in C, array indices are 0-based. `i=1; i<=3; ...` -> `i = 0; i < 3; ...` and so on. – Bob__ Jan 11 '22 at 23:52

1 Answers1

1

initialization

Always initialize your variables because when you don't initialize it, it will have a "garbage" value. You had problems reading the values because of the garbage value in row_total.

https://stackoverflow.com/a/1597426/17652416


Arrays

Pay attention that arrays start from 0 not 1 so if the amount of rows is 4 for example, the rows will be - 0, 1, 2, 3 and not 1, 2, 3, 4. So the iterations should start from i = 0; i < 4 and not i = 1; i <= 4.

More about arrays in C


Fixed initialization

Defines

    #define ROWS 3
    #define COLS 4
    int a[ROWS][COLS] = { 0 };
    int row = 0, col = 0;
    int row_total = 1;
    printf("Enter matrix values : \n");
    //Get the values for the matrix from the user
    for (row = 0; row < ROWS; row++) 
    {
        for (col = 0; col < COLS; col++)
        {
            scanf("%d", &a[row][col]);
        }
            
    }


Iterating on the rows - the answer

    //Print the product of every row
    for (row = 0; row < ROWS; row++)
    {
        row_total = 1;
        for (col = 0; col < COLS; col++)
        {
            row_total *= a[row][col];
        }
        printf("The product of row %d is: %d\n", row, row_total);
    }

Tomer Cher
  • 37
  • 7