0% found this document useful (0 votes)
27 views18 pages

MCT-242L CP1 2022 LM16 33

The document describes a lab assignment on arrays in C language. It introduces passing arrays as function parameters and defines arrays. It includes tasks to write functions to calculate the determinant of 2x2 and 3x3 matrices, find the transpose of a 3x3 matrix, and develop a Tic-Tac-Toe game using a 2D character array to represent the game board and prompt players to select slots.

Uploaded by

Eman Ijaz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views18 pages

MCT-242L CP1 2022 LM16 33

The document describes a lab assignment on arrays in C language. It introduces passing arrays as function parameters and defines arrays. It includes tasks to write functions to calculate the determinant of 2x2 and 3x3 matrices, find the transpose of a 3x3 matrix, and develop a Tic-Tac-Toe game using a 2D character array to represent the game board and prompt players to select slots.

Uploaded by

Eman Ijaz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

LAB 16: MORE ON ARRAYS IN C LANGAUGE

MCT-242L: Computer Programming-I Lab (Fall-2022)


Registration No. 2022-MC-33
OBJECTIVE:
This lab will introduce the concept of user-defined functions with arrays as formal parameter for
a C Language Program. At the end of this lab, you should be able to:
• Pass arrays as formal parameters to a user-defined function
• Apply the concept to find determinant of square matrices
• Develop an interesting game: Tic-Tac-Toe
APPARATUS:
• Laptop\PC with following tools installed
• Visual Studio Code with C/C++ and Code Runner Extensions
• C/C++ mingw-w64 tools for Windows 10

FUNCTIONS AND ARRAYS

Passing Arrays to Functions


If you want to pass a single-dimension array as an argument in a function, you will have to
declare a formal parameter in one of following three ways and all three declaration methods
produce similar results because each tells the compiler that an integer pointer is going to be
received. Similarly, you can pass multi-dimensional arrays as formal parameters.
In C, when you declare an array, the array name itself represents the memory address of the first
element of the array. This memory address is essentially a pointer to the beginning of the array.
When you pass an array to a function, you're actually passing this memory address, which points
to the first element of the array.
So when it is said that the array name is automatically treated as a pointer to the first element of
the array, it is automatically converted to a pointer pointing to the first element of the array. This
means that the function has access to the entire array, not just the first element. The pointer
allows the function to navigate through the array by incrementing the memory address. This is a
convenience in C, allowing you to work with arrays in a way that is similar to working with
pointers.
• Formal Parameters as a Pointer
void myFunction(int *param)
{
.
.
.
}

• Formal Parameters as a Sized Array


void myFunction(int param[10])
{
.
.
.
}

• Formal Parameters as an Unsized Array


void myFunction(int param[])
{
.
.
.
}

Now, consider the following function, which takes an array as an argument along with another
argument and based on the passed arguments, it returns the average of the numbers passed
through the array as follows:
Example 16.1: Passing Array to a Function
/* Example_16_1.c: Passing Array to a Function
----------------------------------------------------------------
This program demonstrates the idea of passing array to a function
in C language. User-defined function getAverage takes and array
as argument and returns the average of its elements.
----------------------------------------------------------------
Written by Shujat Ali (engrshujatali@gmail.com) on 11-Nov-2021.
IDE: Visual Studio Code 1.60.0
C Compiler: GCC (Rev. 5, Built by MSYS2 Project) 10.3.0 */

#include <stdio.h>

// function declaration
double getAverage(int arr[], int arrsize);

int main()
{
int balance[5] = {10, 2, 3, 17, 50};
double avgValue;

// pass pointer to the array as an argument


avgValue = getAverage( balance, 5 );

// output the returned value


printf( "Average value is %.2f ", avgValue );

return 0;
}

// function definition
double getAverage(int arr[], int arrSize)
{
int i;
double avg, sum;

for (i = 0; i < arrSize; ++i)


{
sum += arr[i];
}

avg = sum / arrSize;


return avg;
}

// End of program
Program Output Average value is 16.40

As you can see, the length of the array doesn't matter as far as the function is concerned because
C performs no bounds checking for formal parameters.

Create a Visual Studio Code Workspace, Lab_16 and c files (Task_16_1.c to Task_16_5.c) for
individual tasks and add them to Lab_16 workspace.

TASK 16.1: Determinant of a 2x2 Matrix [2 points]


Write a function determinant_2x2() that takes a 2x2 matrix represented
by a 2-D array and returns it determinant. In main(), ask the user to
enter the 2x2 matrix, calculate its determinant using function, and
display it on screen.
Sample Output Define Matrix A (2x2)
Enter a11 >> 6
Enter a12 >> 3
Enter a21 >> 2
Enter a22 >> 5
A = |a11 a12| = |6.00 3.00|
|a21 a22| |2.00 5.00|

Determinant of A
det(A) = 24.00

Answer:
#include <stdio.h>
int determinant1(int matrix[2][2])
{
int determinant = 0;
determinant = (matrix[0][0] * matrix[1][1]) - (matrix[0][1] * matrix[1][0]);
printf("The determinant of this matrix is %d\n", determinant);
return determinant;
}

int main()
{
int matrix[2][2];
printf("Enter a 2x2 matrix:\n");
// taking inputs for the matrix
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
printf("Enter element at position [%d] [%d]", i + 1, j + 1);
scanf("%d", &matrix[i][j]);
}
}
// displaying the matrix
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
determinant1(matrix);
return 0;
}

TASK 16.2: Determinant of a 3x3 Matrix [3 points]


Write a function determinant_3x3() that takes a 3x3 matrix represented
by a 2-D array and returns it determinant. In main(), ask the user to
enter the 3x3 matrix, calculate its determinant using function, and
display it on screen.
Note: You must use determinant_2x2() inside determinant_3x3() for
calculating determinant of a 2x2 matrix.
Sample Output Define Matrix A (3x3)
Enter a11 >> 2
Enter a12 >> -3
Enter a13 >> 1
Enter a21 >> 2
Enter a22 >> 0
Enter a23 >> -1
Enter a31 >> 1
Enter a32 >> 4
Enter a33 >> 5

|a11 a12 a13| |2.00 -3.00 1.00|


A = |a21 a22 a23| = |2.00 0.00 -1.00|
|a31 a32 a33| |1.00 4.00 5.00|

Determinant of A
det(A) = 49.00

Answer:
#include <stdio.h>
int determinantof3x3(int matrix[3][3])
{
int determinant;
determinant = (matrix[0][0] * ((matrix[1][1] * matrix[2][2]) - (matrix[1][2] * matrix[2][1]))) -
(matrix[0][1] * ((matrix[1][0] * matrix[2][2]) - (matrix[1][2] * matrix[2][0]))) + (matrix[0][2] *
((matrix[1][0] * matrix[2][1]) - (matrix[1][1] * matrix[2][0])));
printf("The determinant of this matrix is %d", determinant);
return determinant;
}
int main()
{
int matrix[3][3];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
printf("Enter element at position [%d] [%d]", i + 1, j + 1);
scanf("%d", &matrix[i][j]);
}
}
// displaying the matrix
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
determinantof3x3(matrix);
}

TASK 16.3: Transpose of a 3x3 Matrix [3 points]


Write a function transpose_3x3() (return type void) that takes a 3x3
matrix represented by a 2-D array and returns it transpose. In main(),
ask the user to enter the 3x3 matrix, calculate its transpose using
function, and display it on screen.
Define Matrix A (3x3)
Enter a11 >> 2
Enter a12 >> -3
Enter a13 >> 1
Enter a21 >> 2
Enter a22 >> 0
Enter a23 >> -1
Enter a31 >> 1
Enter a32 >> 4
Sample Output Enter a33 >> 5

|a11 a12 a13| |2.00 -3.00 1.00|


A = |a21 a22 a23| = |2.00 0.00 -1.00|
|a31 a32 a33| |1.00 4.00 5.00|

Transpose of A
| 2.00 2.00 1.00|
At = |-3.00 0.00 4.00|
| 1.00 -1.00 5.00|

Answer:
#include <stdio.h>
int transposeof3x3(int matrix[3][3])
{
printf("The transpose of this matrix is:");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
printf("%d\t", matrix[j][i]);
}

printf("\n");
}
}
int main()
{
int matrix[3][3];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
printf("Enter element at position [%d] [%d]", i + 1, j + 1);
scanf("%d", &matrix[i][j]);
}
}
// displaying the matrix
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
transposeof3x3(matrix);
}

TASK 16.4: Tic-Tac-Toe Game [5 points]


Write a program for a Tic-Tac-Toe game between two players. You will
show a 3x3 grid to the players with empty slots. Player 1 will use
symbol (X) and player 2 will use (O). Ask players to select the slot
number and fill that with X or O depending upon the player having the
turn. At any stage if the player wins, terminate your program and
display the result.
You should follow these steps:
• Define a 3x3 array (e.g. grid) of character data type and
initialize all of its elements by a space (empty grid).
• Ask player 1 to select a slot (0-8). Then apply logic to assign
‘X’ to the respective array location. For example, if player 1
selects slot number 5, then you should assign grid[1][2]= ‘X’.
• Display the grid with updated slot values.
• Check for the condition of winning. You have three conditions in
row, three in column and two in diagonal (total 8).
• If the winning condition is false, ask for player 2 to select his
slot. Again, apply the logic to assign ‘O’ to the respective array
location.
• Display the grid with updated slot values.
• Check for the condition of winning.
• If the winning condition is false and total turns are less than 9,
go back to step 2 using a while loop.
Sample Output Welcome to Tic-Tac-Toe Game! It will be fun, so let's
begin.
| | | |
-------
| | | |
-------
| | | |

Player-1 please enter slot number (0-8) >> 4


| | | |
-------
| |X| |
-------
| | | |

Player-2 please enter slot number (0-8) >> 1


| |O| |
-------
| |X| |
-------
| | | |

Player-1 please enter slot number (0-8) >> 6


| |O| |
-------
| |X| |
-------
|X| | |

Player-2 please enter slot number (0-8) >> 2


| |O|O|
-------
| |X| |
-------
|X| | |

Player-1 please enter slot number (0-8) >> 0


|X|O|O|
-------
| |X| |
-------
|X| | |
Player-2 please enter slot number (0-8) >> 0
You have entered an invalid move.
Slot 0 is already occupied! Please Try Again!
Player-2 please enter a valid slot number >> 3
|X|O|O|
-------
|O|X| |
-------
|X| | |

Player-1 please enter slot number (0-8) >> 8


|X|O|O|
-------
|O|X| |
-------
|X| |X|

Player-1 won the game!

Answer:
#include <stdio.h>
void displayboard(char grid[3][3])
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
printf("%c ", grid[i][j]);
}
printf("\n");
}
}
int checkwin(char grid[3][3], char player)
{
for (int i = 0; i < 3; i++)
{
if ((grid[i][0] == player && grid[i][1] == player && grid[i][2] == player) || (grid[0][i] == player
&& grid[1][i] == player && grid[2][i] == player))
{
return 1;
}
if ((grid[0][0] == player && grid[1][1] == player && grid[2][2] == player) || (grid[0][2] ==
player && grid[1][1] == player && grid[2][0] == player))
{
return 1;
}
}
}
int main()
{
char grid[3][3] = {{' ', ' ', ' '}, {' ', ' ', ' '}, {' ', ' ', ' '}};
int slot;
char currentPlayer = 'X';
int turns = 0;
while (turns < 9)
{
displayboard(grid);
printf("Player %c, enter your move (0-8): ", currentPlayer);
scanf("%d", &slot);
int row = slot / 3;
int column = slot % 3;
if (grid[row][column] == ' ')
{
grid[row][column] = currentPlayer;
if (checkwin(grid, currentPlayer) == 1)
{
displayboard(grid);
printf("player %c has won", currentPlayer);
return 0;
}
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
turns++;
}
else
{
printf("Slot already occupied. Try again.\n");
}
}
displayboard(grid);
printf("It's a draw!\n");

return 0;
}

TASK 16.5: Connect-4 Game [5 points]


Write a program for a Connect-4 game between two players. You will show
a 6x7 grid to the players with empty slots. Player 1 will use symbol
(X) and player 2 will use (O). Ask players to select the slot number
and fill that with X or O depending upon the player having the turn. At
any stage if the player wins, terminate your program and display the
result.
You should follow these steps:
• Define a 6x7 array (e.g., grid) of character data type and
initialize all its elements by a space (empty grid).
• Ask player 1 to select a slot (0-6). Then apply logic to assign
‘X’ to the respective array location. For example, if player 1
selects slot number 5, then you should assign ‘X’ to grid[i][5]
where i is the highest non-empty row number.
• Display the grid with updated slot values.
• Check for the condition of winning. You have 24 conditions in
rows, 21 in columns and 24 in diagonals (total 69).
• If the winning condition is false, ask for player 2 to select his
slot. Again, apply the logic to assign ‘O’ to the respective array
location.
• Display the grid with updated slot values.
• Check for the condition of winning.
• If the winning condition is false and total turns are less than
42, go back to step 2 using a while loop.
Sample Output Welcome to Connect-4 Game! It will be fun, so let's
begin.
|0|1|2|3|4|5|6|

| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
---------------

Player-1 please enter slot number (0-6) >> 3


|0|1|2|3|4|5|6|

| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | |X| | | |
---------------

Player-2 please enter slot number (0-6) >> 5


|0|1|2|3|4|5|6|

| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | |X| |O| |
---------------

Player-1 please enter slot number (0-6) >> 4


|0|1|2|3|4|5|6|

| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | |X|X|O| |
---------------

Player-2 please enter slot number (0-6) >> 2


|0|1|2|3|4|5|6|

| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | |O|X|X|O| |
---------------

Player-1 please enter slot number (0-6) >> 3


|0|1|2|3|4|5|6|

| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | |X| | | |
| | |O|X|X|O| |
---------------

Player-2 please enter slot number (0-6) >> 2


|0|1|2|3|4|5|6|

| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | |O|X| | | |
| | |O|X|X|O| |
---------------

Player-1 please enter slot number (0-6) >> 2


|0|1|2|3|4|5|6|

| | | | | | | |
| | | | | | | |
| | | | | | | |
| | |X| | | | |
| | |O|X| | | |
| | |O|X|X|O| |
---------------

Player-2 please enter slot number (0-6) >> 4


|0|1|2|3|4|5|6|

| | | | | | | |
| | | | | | | |
| | | | | | | |
| | |X| | | | |
| | |O|X|O| | |
| | |O|X|X|O| |
---------------

Player-1 please enter slot number (0-6) >> 3


|0|1|2|3|4|5|6|

| | | | | | | |
| | | | | | | |
| | | | | | | |
| | |X|X| | | |
| | |O|X|O| | |
| | |O|X|X|O| |
---------------

Player-2 please enter slot number (0-6) >> 3


|0|1|2|3|4|5|6|

| | | | | | | |
| | | | | | | |
| | | |O| | | |
| | |X|X| | | |
| | |O|X|O| | |
| | |O|X|X|O| |
---------------

Player-1 please enter slot number (0-6) >> 2


|0|1|2|3|4|5|6|

| | | | | | | |
| | | | | | | |
| | |X|O| | | |
| | |X|X| | | |
| | |O|X|O| | |
| | |O|X|X|O| |
---------------

Player-2 please enter slot number (0-6) >> 1


|0|1|2|3|4|5|6|

| | | | | | | |
| | | | | | | |
| | |X|O| | | |
| | |X|X| | | |
| | |O|X|O| | |
| |O|O|X|X|O| |
---------------

Player-1 please enter slot number (0-6) >> 1


|0|1|2|3|4|5|6|

| | | | | | | |
| | | | | | | |
| | |X|O| | | |
| | |X|X| | | |
| |X|O|X|O| | |
| |O|O|X|X|O| |
---------------

Player-2 please enter slot number (0-6) >> 1


|0|1|2|3|4|5|6|

| | | | | | | |
| | | | | | | |
| | |X|O| | | |
| |O|X|X| | | |
| |X|O|X|O| | |
| |O|O|X|X|O| |
---------------
Player-1 please enter slot number (0-6) >> 1
|0|1|2|3|4|5|6|

| | | | | | | |
| | | | | | | |
| |X|X|O| | | |
| |O|X|X| | | |
| |X|O|X|O| | |
| |O|O|X|X|O| |
---------------

Game Over!
Player-1 won the game!

Answer:
#include <stdio.h>

// Function to display the Connect-4 board


void displayBoard(char grid[6][7])
{
printf("\nConnect-4\n");
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 7; j++)
{
printf("%c ", grid[i][j]);
}
printf("\n");
}
}

int checkWin(char grid[6][7], char player)


{

for (int i = 0; i < 6; i++)


{
for (int j = 0; j < 4; j++)
{
if (grid[i][j] == player && grid[i][j + 1] == player &&
grid[i][j + 2] == player && grid[i][j + 3] == player)
{
return 1; // Player has won
}
}
}
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 7; j++)
{
if (grid[i][j] == player && grid[i + 1][j] == player &&
grid[i + 2][j] == player && grid[i + 3][j] == player)
{
return 1;
}
}

// Check diagonals (bottom-left to top-right)


for (int i = 3; i < 6; i++)
{
for (int j = 0; j < 4; j++)
{
if (grid[i][j] == player && grid[i - 1][j + 1] == player &&
grid[i - 2][j + 2] == player && grid[i - 3][j + 3] == player)
{
return 1;
}
}
}

// Check diagonals (top-left to bottom-right)


for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
{
if (grid[i][j] == player && grid[i + 1][j + 1] == player &&
grid[i + 2][j + 2] == player && grid[i + 3][j + 3] == player)
{
return 1;
}
}
}

return 0; // No winner yet


}

int main()
{
char grid[6][7] = {
{' ', ' ', ' ', ' ', ' ', ' ', ' '},
{' ', ' ', ' ', ' ', ' ', ' ', ' '},
{' ', ' ', ' ', ' ', ' ', ' ', ' '},
{' ', ' ', ' ', ' ', ' ', ' ', ' '},
{' ', ' ', ' ', ' ', ' ', ' ', ' '},
{' ', ' ', ' ', ' ', ' ', ' ', ' '}};

int slot;
char currentPlayer = 'X';

int turns = 0;
while (turns < 42)
{

displayBoard(grid);

printf("Player %c, enter your move (0-6): ", currentPlayer);


scanf("%d", &slot);

for (int i = 5; i >= 0; i--)


{
if (grid[i][slot] == ' ')
{
grid[i][slot] = currentPlayer;
break;
}
}

if (checkWin(grid, currentPlayer))
{
displayBoard(grid);
printf("Player %c wins!\n", currentPlayer);
return 0;
}

currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';

turns++;
}

// If no one wins after 42 turns, it's a draw


displayBoard(grid);
printf("It's a draw!\n");

return 0;
}
Students are advised to fill the manual and submit it before the upcoming lab. Kindly rename the file as
‘MCT-242L_CP1_2022_LM16_XX’, where XX is your roll number. After completing the manual, turn it in Google
Classroom.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy