Arrays 2D
Quiz 3 on 10/20/2025 on lab
Two-D example
int mult[5][6];
(5 is the number of rows, 6 is the number of columns(boxes in each row)
mult has a box of five rows of six boxes
for memory, it goes row by row, starting from the first row, and the last box of the first row is ahead of the new row.
Memory of just the rows are just 1D arrays
you can use functions with 1D requirements due to thing above
Second index needs to be filled in so that the computer needs to know where it is
memory: first index times seond index + second index would be where the memory is stored
Mult example
// Arup Guha
// 10/10/2012
// Stores a multiplication table in a 2D array and prints it.
#include <stdio.h>
#define SIZE 10
int main(void) {
int i,j;
int table[SIZE][SIZE];
// Fills my multiplication table.
for (i=0; i<SIZE; i++)
for (j=0; j<SIZE; j++)
table[i][j] = (i+1)*(j+1);
// Print the table.
for (i=0; i<SIZE; i++) {
// Print one row.
for (j=0; j<SIZE; j++)
printf("%4d", table[i][j]);
// Go to next row.
printf("\n");
}
return 0;
}Pascal Triangle
// Arup Guha
// 11/8/05
// Example to illustrate a use of 2-D arrays that prints out the first
// ten rows of Pascal's Triangle.
#include <stdio.h>
int main() {
int pascaltri[11][11];
int i,j;
// Initialize the beginning and end of each row.
for (i=0; i<11; i++) {
pascaltri[i][0] = 1;
pascaltri[i][i] = 1;
}
// Fills in triangle, using the pascal triangle identity.
for (i=2; i<11; i++)
for (j=1; j<i; j++)
pascaltri[i][j] = pascaltri[i-1][j-1]+pascaltri[i-1][j];
// Prints out chart.
for (i=0; i<11; i++) {
for (j=0; j<=i; j++)
printf("%4d ", pascaltri[i][j]);
printf("\n");
}
return 0;
}row 30 is max without overflow
Get tea/*** EDITED on 10/20/2025 to solve a permutation problem. ***/ #include <stdio.h> #define SIZE 31 int numorders(int freq[], int length, int tri[][SIZE]); int sum(int arr[], int length); int main() { int pascaltri[SIZE][SIZE]; int i,j; // Initialize the beginning and end of each row. for (i=0; i<SIZE; i++) { pascaltri[i][0] = 1; pascaltri[i][i] = 1; } // Fills in triangle, using the pascal triangle identity. for (i=2; i<SIZE; i++) for (j=1; j<i; j++) pascaltri[i][j] = pascaltri[i-1][j-1]+pascaltri[i-1][j]; int freq[3]; freq[0] = 3; freq[1] = 4; freq[2] = 5; int res = numorders(freq, 3, pascaltri); printf("number of arrangements is %d\n", res); return 0; } /*** Might overflow sometimes... ***/ // Returns the number of permutations of the objects described in freq. // freq has length length, and freq[i] indicates that there are freq[i] // copies of the object i. For example if freq = {3,4,5}, then this // returns C(12,3)*C(9,4), the total number of permutations of // 0,0,0,1,1,1,1,2,2,2,2,2. int numorders(int freq[], int length, int tri[][SIZE]) { int total = sum(freq, length); // Default result. int res = 1; // I stop one short because my formula has length-1 terms. for (int i=0; i<length-1; i++) { // This is the remaining total slots open choose the number of item i // we are placing. res = res* tri[total][freq[i]]; // I just placed freq[i] objects, so this is how many fewer slots I have left. total -= freq[i]; } return res; } // Returns the sum of the values in arr from index 0 to index length-1, inclusive. int sum(int arr[], int length) { // Add up each value. int total = 0; for (int i=0; i<length; i++) total += arr[i]; // This is the sum. return total; }
cher code
/*** EDITED on 10/20/2025 to solve a permutation problem. ***/
#include <stdio.h>
#define SIZE 31
int numorders(int freq[], int length, int tri[][SIZE]);
int sum(int arr[], int length);
int main() {
int pascaltri[SIZE][SIZE];
int i,j;
// Initialize the beginning and end of each row.
for (i=0; i<SIZE; i++) {
pascaltri[i][0] = 1;
pascaltri[i][i] = 1;
}
// Fills in triangle, using the pascal triangle identity.
for (i=2; i<SIZE; i++)
for (j=1; j<i; j++)
pascaltri[i][j] = pascaltri[i-1][j-1]+pascaltri[i-1][j];
int freq[3];
freq[0] = 3; freq[1] = 4; freq[2] = 5;
int res = numorders(freq, 3, pascaltri);
printf("number of arrangements is %d\n", res);
return 0;
}
/*** Might overflow sometimes... ***/
// Returns the number of permutations of the objects described in freq.
// freq has length length, and freq[i] indicates that there are freq[i]
// copies of the object i. For example if freq = {3,4,5}, then this
// returns C(12,3)*C(9,4), the total number of permutations of
// 0,0,0,1,1,1,1,2,2,2,2,2.
int numorders(int freq[], int length, int tri[][SIZE]) {
int total = sum(freq, length);
// Default result.
int res = 1;
// I stop one short because my formula has length-1 terms.
for (int i=0; i<length-1; i++) {
// This is the remaining total slots open choose the number of item i
// we are placing.
res = res* tri[total][freq[i]];
// I just placed freq[i] objects, so this is how many fewer slots I have left.
total -= freq[i];
}
return res;
}
// Returns the sum of the values in arr from index 0 to index length-1, inclusive.
int sum(int arr[], int length) {
// Add up each value.
int total = 0;
for (int i=0; i<length; i++)
total += arr[i];
// This is the sum.
return total;
}Gridwalking
Good exercise could be error checks'
C can do array-outofbounds, it’s up to the programmer to make sure it is inbounds.
// Arup Guha
// 10/10/2018
// Prints out a grid and allows the user to move through it going
// up, down, left and right. No error checking is done, so this is
// an excellent program to download and edit to make improvements or
// modifications to.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROWS 5
#define COLS 8
void printGrid(int grid[][COLS]);
// Possible directions of movement.
const int DX[] = {-1, 1, 0, 0};
const int DY[] = {0, 0,-1, 1};
int main(void) {
srand(time(0));
int i, j, grid[ROWS][COLS];
// Make everything an empty square.
for (i=0; i<ROWS; i++)
for (j=0; j<COLS; j++)
grid[i][j] = 0;
// I randomly place you.
int x = rand()%ROWS;
int y = rand()%COLS;
grid[x][y] = 1;
// Get the direction.
int dir;
printGrid(grid);
printf("Do you want to go Up(0), Down(1), Left(2), Right(3), Quit(4)?\n");
scanf("%d", &dir);
// Keep on going till they quit.
while (dir != 4) {
// Move me!
int savex = x;
int savey = y;
x += DX[dir];
y += DY[dir];
// Update the grid accordingly.
grid[savex][savey] = 0;
grid[x][y] = 1;
// Get next move.
printGrid(grid);
printf("Do you want to go Up(0), Down(1), Left(2), Right(3), Quit(4)?\n");
scanf("%d", &dir);
}
return 0;
}
void printGrid(int grid[][COLS]) {
int i,j;
// Go through each row.
for (i=0; i<ROWS; i++) {
// Print one row, * = me!
for (j=0; j<COLS; j++) {
if (grid[i][j] == 0)
printf("_");
else
printf("*");
}
// Go to the next row.
printf("\n");
}
}Magic square:
1,2,3,….., n²
prints each int in a n by n square
all rows, cols, both class add ot same number and diagonials
1 D Index of i
2D (i/c, i % c)
2D Index of (i,j)
1D i*C +j
Edits: making it work for 4 by 4
use functuons for row check, column and diagonal check, use a loop for the diagonal check
changing the hard coding
#include <stdio.h>
int main() {
int square[3][3], i;
// Read in the user's magic square.
printf("Please enter your magic square.\n");
for (i=0; i<9; i++)
scanf("%d", &square[i/3][i%3]);
// Output the result.
if (checksquare(square))
printf("You have a magic square\n");
else
printf("Not a magic square\n");
}
// Returns 1 if square is a magic square, 0 otherwise.
int checksquare(int square[][3]) {
// Checks the two requirements of a magic square and returns 1 only
// if both are satisfied.
return checknum(square)&&checksum(square);
}
// Returns 1 if the square contains each of the integers from 1 to 9
// exactly once. Returns 0 otherwise.
int checknum(int square[][3]) {
int freq[10];
int i,j;
// Initialize all frequencies to 0.
// Note: We will NOT use index 0 and we will store how many 1s we see
// in index 1, etc.
for (i=0; i<10; i++)
freq[i] = 0;
// Go through each value in the square.
for (i=0; i<3; i++)
for (j=0; j<3; j++) {
// Invalid value - not a magic square.
if (square[i][j] < 1 || square[i][j] > 9)
return 0;
// Adjust the appropriate frequency counter.
freq[square[i][j]]++;
}
// If any number from 1 to 9 doesn't appear once,
// it's not a magic square.
for (i=1; i<10; i++)
if (freq[i] != 1)
return 0;
// Passed all the tests for this function.
return 1;
}
// Returns 1 if the sum of each row, column and diagonal is 15. Returns 0
// otherwise.
int checksum(int square[][3]) {
int i, j, sum;
// check each row
for (i=0; i<3; i++) {
// Here we find the sum of the values on row #i.
sum = 0;
for (j=0; j<3; j++)
sum += square[i][j];
// If this row doesn't pass, immediately return the result.
if (sum != 15)
return 0;
}
// Check each column.
for (j=0; j<3; j++) {
// Here we find the sum of column j.
sum = 0;
for (i=0; i<3; i++)
sum += square[i][j];
// If this column doesn't pass, immediately return the result.
if (sum != 15)
return 0;
}
// check forward diagonal
if (square[0][0]+square[1][1]+square[2][2] != 15)
return 0;
// check backward diagonal
if (square[0][2]+square[1][1]+square[2][0] != 15)
return 0;
// Yeah, it's a magic square!
return 1;
}Tic Tac toe:
// Arup Guha
// 11/5/03
// Tic-Tac-Toe: This program allows for two players to play tic-tac-toe
// against each other.
// Known Bugs: Some error checking is done, but users must still enter the
// correct type of information desired in the proper format.
// For example, if the user enters their square as 1,2 instead
// of 1 2 as specified, a run-time error will occur.
#include <stdio.h>
#define SIZE 3
#define UNFINISHED 0
#define WINX 1
#define WINO 2
#define CATS 3
void init(char board[][SIZE]);
void printboard(char board[][SIZE]);
void domove(char board[][SIZE], char player);
int status(char board[][SIZE]);
int checkrows(char board[][SIZE], char player);
int checkcols(char board[][SIZE], char player);
int checkdiag(char board[][SIZE], char player);
int hasmoveleft(char board[][SIZE]);
char getplayer(int turn);
int main() {
char board[SIZE][SIZE];
int i,j, result;
int turn = 0; // Set the current turn to player X
init(board);
// Play until the game is over.
while (status(board) == UNFINISHED) {
// Execute a turn and change who's move it is.
domove(board, getplayer(turn));
turn = (turn+1)%2;
}
result = status(board);
// Output the appropriate message for each possible outcome.
if (result == WINX)
printf("Congrats team X, you won!\n");
else if (result == WINO)
printf("Congrats team O, you won!\n");
else
printf("Good job to both teams, the outcome is a tie!\n");
return 0;
}
// Returns the character corresponding to the player number. Player 0 is
// character 'X' and player 1 is character 'O'.
char getplayer(int turn) {
if (turn == 0)
return 'X';
return 'O';
}
// Initializes the board to hold all underscore('_') characters.
void init(char board[][SIZE]) {
int i, j;
for (i=0; i<SIZE; i++)
for (j=0; j<SIZE; j++)
board[i][j] = '_';
}
// Prints out the board in a readable format with rows and columns
// labelled.
void printboard(char board[][SIZE]) {
int i, j;
// Print out labels.
printf("Col->\t");
for (i=0; i<SIZE; i++)
printf("%d ", i);
printf("\nRow\n");
// Print out each board entry.
for (i=0; i<SIZE; i++) {
printf("%d\t",i);
for (j=0; j<SIZE; j++)
printf("%c ",board[i][j]);
printf("\n");
}
}
// Executes a move for the player specified by the second parameter and
// reflects those changes on the board.
void domove(char board[][SIZE], char player) {
int done = 0;
int r, c;
// Continue until a move has been executed.
while (!done) {
// Prompt for and read in the player's move.
printf("Here is the current board:\n");
printboard(board);
printf("Enter your move, player %c.\n", player);
printf("Enter the row(0-%d) followed by a space and the col(0-%d).\n", SIZE-1, SIZE-1);
scanf("%d%d", &r, &c);
// Check for invalid indexes.
if (r<0 || r>=SIZE || c<0 || c>=SIZE)
printf("Sorry, that is not a valid square.\n");
// Check for a taken square.
else if (board[r][c] != '_')
printf("Sorry, that square has been taken already.\n");
// Execute the move.
else {
board[r][c] = player;
done=1;
}
}
}
// Returns the status of the board. Either X has won, O has won, the game
// is unfinished or it's a cats game.
int status(char board[][SIZE]) {
if (checkrows(board,'X') || checkcols(board,'X') || checkdiag(board,'X'))
return WINX;
if (checkrows(board,'O') || checkcols(board,'O') || checkdiag(board,'O'))
return WINO;
if (hasmoveleft(board))
return UNFINISHED;
return CATS;
}
// Returns 1 if there is a blank square on the board, 0 otherwise.
int hasmoveleft(char board[][SIZE]) {
int i,j;
// Check for blank square.
for (i=0; i<SIZE; i++)
for (j=0; j<SIZE; j++)
if (board[i][j] == '_')
return 1;
return 0;
}
// Returns true if player has all three squares in any row.
int checkrows(char board[][SIZE], char player) {
int row, col, check;
// Check all rows one by one, to see if player has all squares.
for (row=0; row<SIZE; row++) {
check = 0;
for (col=0; col<SIZE; col++)
// Count all squares that player has on a row.
if (board[row][col] == player)
check++;
// Player has all squares on a row.
if (check == SIZE)
return 1;
}
return 0;
}
// Returns true if player has all three squares in any row.
int checkcols(char board[][SIZE], char player) {
int row, col, check;
for (col=0; col<SIZE; col++) {
check = 0;
for (row=0; row<SIZE; row++)
// Count # squares player has on a column.
if (board[row][col] == player)
check++;
// Player has all squares on a column.
if (check == SIZE)
return 1;
}
return 0;
}
// Returns 1 if player owns a diagonal, 0 otherwise.
int checkdiag(char board[][SIZE], char player) {
int row;
int check=0;
// Check forward diagonal.
for (row=0; row<SIZE; row++)
if (board[row][row] == player)
check++;
if (check == SIZE)
return 1;
// Check backward diagonal.
check=0;
for (row=0; row<SIZE; row++)
if (board[SIZE-1-row][row] == player)
check++;
if (check == SIZE)
return 1;
return 0;
}Connect 4
Issue: array out of bound
(write inbound function and call it before indexing the array)
have to check every square in every direction
for a char array, one space has to be for the Null.
const is constant!
Minesweeper
numbers are based on number of adajcent bombs
Recursion is taught in CS1(surpisied but not really)
Real ONE= waits after 1st click to generate bombs
This Version= randomly generates the bombs
Convert integers to char
char nChr = (char)(‘0’ +n);
Convert char to integers
int n = nChr - ‘0’;
Count # of all adjacent bombs?
Dx/Dy arrays or double for loop, skip dx = 0, dy = 0;