UP | HOME

HW21
COP-3223H

Setup

See HW7's Setup for how to prepare for performing and submitting your homework.

Homework file names

  • hw21-1.c
  • hw21-2.c

Question

  1. (hw21-1.c) Write a program that replace each value with its square in a 3x5 matrix, then prints it out. You can use the following skeleton code:

    #include <stdio.h>
    #include <unistd.h>
    
    int main(int argc, char **argv) {
      int a[3][5] = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15} };
      int width = 3;
      int height = 5;
    
      // add your implementation here
    
      return 0;
    }
    
  2. (hw21-2.c) Rewrite the tic-tac-toe program in class to use a multidimensional (3x3) array instead of a single 9-element array. Below is the single array version.

    #include <stdio.h>
    #include <assert.h>
    
    int main(int argc, char **argv) {
      char c = '\0';
    
      char board[] = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };
      int boardlen = 9;
    
      // turn 0 is x, turn 1 is o.
      int turn = 0;
      while (1) {
        printf("\x1b[2J");
        printf("\x1b[H");
        for (int i = 0; i < boardlen; i++) {
          putchar(board[i]);
          if ((i % 3) == 2) {
            putchar('\n');
          }
        }
        printf("last turn: %c\n", c);
        switch (turn) {
        case 0:
          printf("X's turn\n");
          break;
        case 1:
          printf("O's turn\n");
          break;
        default:
          assert(0);
        }
        scanf("%c", &c);
        int index = - 1;
    
        switch (c) {
        case '1':
          index = 0;
          break;
        case '2':
          index = 1;
          break;
        case '3':
          index = 2;
          break;
        case '4':
          index = 3;
          break;
        case '5':
          index = 4;
          break;
        case '6':
          index = 5;
          break;
        case '7':
          index = 6;
          break;
        case '8':
          index = 7;
          break;
        case '9':
          index = 8;
          break;
        default:
          index = -1;
          break;
        }
    
        if (0 <= index && index < 9 && !('X' == board[index] || 'O' == board[index])) {
          switch (turn) {
          case 0:
            board[index] = 'X';
            turn = 1;
            break;
          case 1:
            board[index] = 'O';
            turn = 0;
            break;
          default:
            assert(0);
            break;
          }
        }
      }
    }
    

Submission

See HW7's Submission instructions for adding, committing, and pushing your homework to the assignments' repo.

Self-check

See HW7's Self-check for instructions on checking what you have submitted to the remote grading repository.

Author: Paul Gazzillo

Created: 2026-03-04 Wed 10:21

Validate