C - Making a two-dimensional array

Introduction

You can think of a two-dimensional array as a grid of rows and columns.

An example of this type of array is a chess board - a grid of 8 rows and 8 columns.

A two-dimensional array is declared as follows:

int chess[8][8]; 

The two square brackets define two different dimensions of the chess array: 8 rows and 8 columns.

The square located at the first row and column would be referenced as chess[0][0].

The last square on that row would be chess[0][7], and the last square on the board would be chess[7][7].

The following code creates a simple tic-tac-toe board using a two-dimensional matrix: 3-by-3.

Demo

#include <stdio.h> 

int main() //  w  ww  . j av  a2  s .c  o m
{ 
    char tictactoe[3][3]; 
    int x,y; 

/* initialize matrix */ 
    for(x=0;x<3;x++) 
        for(y=0;y<3;y++) 
            tictactoe[x][y]='.'; 
    tictactoe[1][1] = 'X'; 

/* display game board */ 
    puts("Ready to play Tic-Tac-Toe?"); 
      for(x=0;x<3;x++) 
      { 
          for(y=0;y<3;y++) 
              printf("%c\t",tictactoe[x][y]); 
          putchar('\n'); 
      } 
      return(0); 
  }

Result

Related Topic