How to calculate the cell number of a matrix (2D array) in C

1 Answer

0 votes
#include <stdio.h>
  
#define ROWS 5
#define COLS 4
  
int main(void) {
    int matrix[ROWS][COLS] = {
                { 0,  1,  2,  3},
                { 4,  5,  6,  7},
                { 8,  9, 10, 11},
                {12, 13, 14, 15},                
                {16, 17, 18, 10}
    };
      
    int x = 2, y = 2;
    printf("%d\n", x * COLS + y);
 
    x = 3, y = 2;
    printf("%d\n", x * COLS + y);
 
    return 0;
}
  
  
  
  
/*
run:
  
10
14
  
*/

 



answered Feb 18, 2021 by avibootz
edited Feb 19, 2021 by avibootz
...