0% found this document useful (0 votes)
18 views

Lab 01

The document contains 4 questions and solutions regarding 3D arrays in C++. Question 1 involves reading temperature data into a 3D array and finding the maximum temperature and its coordinates. Question 2 develops functions to manage warehouse inventory stored in a 3D array. Question 3 simulates a 3D tic-tac-toe game using a 3D array to represent the game board. Question 4 populates a 3D array with random values, displays the array, and calculates the total sum.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Lab 01

The document contains 4 questions and solutions regarding 3D arrays in C++. Question 1 involves reading temperature data into a 3D array and finding the maximum temperature and its coordinates. Question 2 develops functions to manage warehouse inventory stored in a 3D array. Question 3 simulates a 3D tic-tac-toe game using a 3D array to represent the game board. Question 4 populates a 3D array with random values, displays the array, and calculates the total sum.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

LAB 01

Question01:
You are provided with a dataset representing temperatures at different points in a room over time. Write
a C++ program to read this dataset into a 3D array. Once the data is loaded, find and display the
maximum temperature recorded in the room along with its location (coordinates) within the array. write
code

Soution:

#include <iostream>

const int ROOM_WIDTH = 5;

const int ROOM_LENGTH = 4;

const int ROOM_HEIGHT = 3;

void findMaxTemperature(const double roomTemperatures[ROOM_HEIGHT][ROOM_LENGTH]


[ROOM_WIDTH]) {

double maxTemperature = roomTemperatures[0][0][0];

int maxX = 0, maxY = 0, maxZ = 0;

for (int z = 0; z < ROOM_HEIGHT; ++z) {

for (int y = 0; y < ROOM_LENGTH; ++y) {

for (int x = 0; x < ROOM_WIDTH; ++x) {

if (roomTemperatures[z][y][x] > maxTemperature) {

maxTemperature = roomTemperatures[z][y][x];

maxX = x;

maxY = y;

maxZ = z;

}
}

std::cout << "Maximum temperature recorded: " << maxTemperature << "°C\n";

std::cout << "Location (X, Y, Z): (" << maxX << ", " << maxY << ", " << maxZ << ")\n";

int main() {

double roomTemperatures[ROOM_HEIGHT][ROOM_LENGTH][ROOM_WIDTH] = {

{{22.5, 23.1, 21.8, 20.3, 24.0}, {25.2, 26.5, 27.8, 28.3, 25.9}, {23.4, 24.7, 26.2, 27.1, 28.6}, {22.8, 21.4,
20.9, 20.1, 19.7}},

{{20.7, 22.3, 23.9, 22.4, 21.1}, {24.6, 25.9, 27.3, 28.6, 25.9}, {22.8, 24.1, 25.6, 27.2, 28.7}, {21.2, 20.8,
20.3, 19.9, 18.7}},

{{18.5, 19.1, 17.8, 16.3, 19.0}, {21.2, 22.5, 23.8, 24.3, 21.9}, {19.4, 20.7, 22.2, 23.1, 24.6}, {18.8, 17.4,
16.9, 16.1, 15.7}}

};

findMaxTemperature(roomTemperatures);

return 0;

Question02:
Design a C++ program to manage inventory in a warehouse using a 3D array. Each element of the array
should represent the quantity of a specific item stored at a particular location (aisle, shelf, bin).
Implement functions to add, remove, and display the quantity of a specific item at a given location.

Soution:
#include <iostream>

const int MAX_AISLES = 5;

const int MAX_SHELVES = 10;


const int MAX_BINS = 10;

// Function to add quantity of an item at a specific location

void addItem(int inventory[MAX_AISLES][MAX_SHELVES][MAX_BINS], int aisle, int shelf, int bin, int
quantity) {

inventory[aisle][shelf][bin] += quantity;

// Function to remove quantity of an item from a specific location

void removeItem(int inventory[MAX_AISLES][MAX_SHELVES][MAX_BINS], int aisle, int shelf, int bin, int
quantity) {

inventory[aisle][shelf][bin] -= quantity;

if (inventory[aisle][shelf][bin] < 0) {

std::cerr << "Error: Insufficient quantity available at specified location.\n";

inventory[aisle][shelf][bin] += quantity; // Revert back to original quantity

// Function to display quantity of an item at a specific location

void displayItemQuantity(const int inventory[MAX_AISLES][MAX_SHELVES][MAX_BINS], int aisle, int


shelf, int bin) {

std::cout << "Quantity of item at location (" << aisle << ", " << shelf << ", " << bin << "): "

<< inventory[aisle][shelf][bin] << std::endl;

int main() {

int warehouseInventory[MAX_AISLES][MAX_SHELVES][MAX_BINS] = {0}; // Initialize inventory to zero

// Example usage:

addItem(warehouseInventory, 2, 3, 1, 50); // Add 50 items to aisle 2, shelf 3, bin 1


displayItemQuantity(warehouseInventory, 2, 3, 1); // Display quantity at specified location

removeItem(warehouseInventory, 2, 3, 1, 20); // Remove 20 items from aisle 2, shelf 3, bin 1

displayItemQuantity(warehouseInventory, 2, 3, 1); // Display updated quantity at specified location

return 0;

Question03:
Develop a C++ program to simulate a 3D Tic-Tac-Toe game using a 3D array. The program should allow
two players to take turns marking cells in the 3D grid. Ensure that the game board is represented using a
3D array, and implement functions to check for winning combinations in all three dimensions.

Soution:
#include <iostream>

const int BOARD_SIZE = 3;

char board[BOARD_SIZE][BOARD_SIZE][BOARD_SIZE];

// Initialize the game board

void initializeBoard() {

for (int i = 0; i < BOARD_SIZE; ++i) {

for (int j = 0; j < BOARD_SIZE; ++j) {

for (int k = 0; k < BOARD_SIZE; ++k) {

board[i][j][k] = ' ';

}
// Display the current state of the board

void displayBoard() {

for (int i = 0; i < BOARD_SIZE; ++i) {

std::cout << "Layer " << i + 1 << ":\n";

for (int j = 0; j < BOARD_SIZE; ++j) {

for (int k = 0; k < BOARD_SIZE; ++k) {

std::cout << board[i][j][k];

if (k < BOARD_SIZE - 1) {

std::cout << " | ";

std::cout << std::endl;

if (j < BOARD_SIZE - 1) {

std::cout << "---------\n";

std::cout << std::endl;

// Check if a player has won the game

bool checkWin(char player) {

// Check rows

for (int i = 0; i < BOARD_SIZE; ++i) {

for (int j = 0; j < BOARD_SIZE; ++j) {

if (board[i][j][0] == player && board[i][j][1] == player && board[i][j][2] == player) {

return true;

}
}

// Check columns

for (int i = 0; i < BOARD_SIZE; ++i) {

for (int j = 0; j < BOARD_SIZE; ++j) {

if (board[i][0][j] == player && board[i][1][j] == player && board[i][2][j] == player) {

return true;

// Check diagonals

for (int i = 0; i < BOARD_SIZE; ++i) {

if (board[i][0][0] == player && board[i][1][1] == player && board[i][2][2] == player) {

return true;

if (board[i][0][2] == player && board[i][1][1] == player && board[i][2][0] == player) {

return true;

// Check layers

for (int i = 0; i < BOARD_SIZE; ++i) {

for (int j = 0; j < BOARD_SIZE; ++j) {

if (board[0][i][j] == player && board[1][i][j] == player && board[2][i][j] == player) {

return true;

}
// Check diagonals in 3D

if (board[0][0][0] == player && board[1][1][1] == player && board[2][2][2] == player) {

return true;

if (board[0][0][2] == player && board[1][1][1] == player && board[2][2][0] == player) {

return true;

if (board[0][2][0] == player && board[1][1][1] == player && board[2][0][2] == player) {

return true;

if (board[0][2][2] == player && board[1][1][1] == player && board[2][0][0] == player) {

return true;

return false;

// Check if the game board is full (tie)

bool checkTie() {

for (int i = 0; i < BOARD_SIZE; ++i) {

for (int j = 0; j < BOARD_SIZE; ++j) {

for (int k = 0; k < BOARD_SIZE; ++k) {

if (board[i][j][k] == ' ') {

return false;

}
return true;

// Main game loop

void playGame() {

char currentPlayer = 'X';

int row, col, layer;

initializeBoard();

while (true) {

std::cout << "Player " << currentPlayer << "'s turn. Enter row, column, and layer (1-3): ";

std::cin >> row >> col >> layer;

// Adjust to 0-based indexing

row--; col--; layer--;

// Check if the cell is empty

if (board[layer][row][col] == ' ') {

board[layer][row][col] = currentPlayer;

displayBoard();

// Check for a win

if (checkWin(currentPlayer)) {

std::cout << "Player " << currentPlayer << " wins!\n";

break;

}
// Check for a tie

if (checkTie()) {

std::cout << "It's a tie!\n";

break;

// Switch player

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

} else {

std::cout << "Cell already occupied. Please try again.\n";

int main() {

std::cout << "Welcome to 3D Tic-Tac-Toe!\n";

playGame();

return 0;

Question04:
Write a C++ program that creates a 3D array of integers. Implement functions to populate the array with
random values, display the array contents, and find the sum of all elements in the array.

Soution:
#include <iostream>

#include <cstdlib> // For rand() and srand()

#include <ctime> // For time()

// Define constants for array dimensions

const int X_DIM = 3;


const int Y_DIM = 3;

const int Z_DIM = 3;

// Function to populate the 3D array with random values

void populateArray(int array[X_DIM][Y_DIM][Z_DIM]) {

// Seed the random number generator

srand(time(NULL));

// Populate the array with random values

for (int x = 0; x < X_DIM; ++x) {

for (int y = 0; y < Y_DIM; ++y) {

for (int z = 0; z < Z_DIM; ++z) {

array[x][y][z] = rand() % 100; // Generate random values between 0 and 99

// Function to display the contents of the 3D array

void displayArray(const int array[X_DIM][Y_DIM][Z_DIM]) {

std::cout << "Array Contents:\n";

for (int x = 0; x < X_DIM; ++x) {

for (int y = 0; y < Y_DIM; ++y) {

for (int z = 0; z < Z_DIM; ++z) {

std::cout << array[x][y][z] << " ";

std::cout << std::endl;

std::cout << std::endl;


}

// Function to find the sum of all elements in the 3D array

int findArraySum(const int array[X_DIM][Y_DIM][Z_DIM]) {

int sum = 0;

for (int x = 0; x < X_DIM; ++x) {

for (int y = 0; y < Y_DIM; ++y) {

for (int z = 0; z < Z_DIM; ++z) {

sum += array[x][y][z];

return sum;

int main() {

int array[X_DIM][Y_DIM][Z_DIM];

// Populate the array with random values

populateArray(array);

// Display the contents of the array

displayArray(array);

// Find the sum of all elements in the array

int sum = findArraySum(array);

std::cout << "Sum of all elements in the array: " << sum << std::endl;
return 0;

Question05:
Create a C++ program that generates a random 3D array of integers. Implement functions to calculate
and display basic statistics such as the sum, average, maximum, and minimum values of the elements in
the array.

Soution:
#include <iostream>

#include <cstdlib> // For rand() and srand()

#include <ctime> // For time()

// Constants for array dimensions

const int X_DIM = 3;

const int Y_DIM = 3;

const int Z_DIM = 3;

// Function to generate a random integer between min and max (inclusive)

int getRandomInt(int min, int max) {

return rand() % (max - min + 1) + min;

// Function to fill the 3D array with random integers

void fillRandomArray(int array[X_DIM][Y_DIM][Z_DIM], int minVal, int maxVal) {

for (int i = 0; i < X_DIM; ++i) {

for (int j = 0; j < Y_DIM; ++j) {

for (int k = 0; k < Z_DIM; ++k) {

array[i][j][k] = getRandomInt(minVal, maxVal);

}
}

// Function to calculate the sum of all elements in the array

int calculateSum(const int array[X_DIM][Y_DIM][Z_DIM]) {

int sum = 0;

for (int i = 0; i < X_DIM; ++i) {

for (int j = 0; j < Y_DIM; ++j) {

for (int k = 0; k < Z_DIM; ++k) {

sum += array[i][j][k];

return sum;

// Function to calculate the average of all elements in the array

double calculateAverage(const int array[X_DIM][Y_DIM][Z_DIM]) {

int sum = calculateSum(array);

return static_cast<double>(sum) / (X_DIM * Y_DIM * Z_DIM);

// Function to find the maximum value in the array

int findMax(const int array[X_DIM][Y_DIM][Z_DIM]) {

int maxVal = array[0][0][0];

for (int i = 0; i < X_DIM; ++i) {

for (int j = 0; j < Y_DIM; ++j) {

for (int k = 0; k < Z_DIM; ++k) {

if (array[i][j][k] > maxVal) {


maxVal = array[i][j][k];

return maxVal;

// Function to find the minimum value in the array

int findMin(const int array[X_DIM][Y_DIM][Z_DIM]) {

int minVal = array[0][0][0];

for (int i = 0; i < X_DIM; ++i) {

for (int j = 0; j < Y_DIM; ++j) {

for (int k = 0; k < Z_DIM; ++k) {

if (array[i][j][k] < minVal) {

minVal = array[i][j][k];

return minVal;

int main() {

// Seed the random number generator

srand(time(NULL));

// Generate random 3D array of integers

int randomArray[X_DIM][Y_DIM][Z_DIM];
fillRandomArray(randomArray, 1, 100); // Fill with random integers between 1 and 100

// Display the random array

std::cout << "Random 3D Array:\n";

for (int i = 0; i < X_DIM; ++i) {

for (int j = 0; j < Y_DIM; ++j) {

for (int k = 0; k < Z_DIM; ++k) {

std::cout << randomArray[i][j][k] << " ";

std::cout << std::endl;

std::cout << std::endl;

// Calculate and display basic statistics

int sum = calculateSum(randomArray);

double average = calculateAverage(randomArray);

int maxVal = findMax(randomArray);

int minVal = findMin(randomArray);

std::cout << "\nBasic Statistics:\n";

std::cout << "Sum: " << sum << std::endl;

std::cout << "Average: " << average << std::endl;

std::cout << "Maximum: " << maxVal << std::endl;

std::cout << "Minimum: " << minVal << std::endl;

return 0;

}
Question 06:
write a c++ code that allows the user to slice a 4d array to exract 3d subarray based on specified
dimensions and indices. implement a function using pointers that takes the orignal 4d array user
defined slicing parameter and returns the sliced 3d array return complete runnig code

Solution:
#include <iostream>

using namespace std;

// Function to take input for the 4D array

void inputArray(int a[2][2][2][2]) {

for (int i = 0; i < 2; i++) {

for (int j = 0; j < 2; j++) {

for (int k = 0; k < 2; k++) {

for (int l = 0; l < 2; l++) {

cout << "Enter value of a[" << i << "][" << j << "][" << k << "][" << l << "]: ";

cin >> a[i][j][k][l];

// Function to slice the 4D array and print the sliced 3D subarray

void sliceAndPrint(int* a, int dim1, int dim2, int dim3, int idx1, int idx2, int idx3) {

cout << "Sliced 3D subarray for dimensions [" << dim1 << "][" << dim2 << "][" << dim3 << "] and indices
[" << idx1 << "][" << idx2 << "][" << idx3 << "]:" << endl;

for (int i = 0; i < 2; i++) {

cout << "[";

for (int j = 0; j < 2; j++) {

cout << "[";


for (int k = 0; k < 2; k++) {

int index1, index2, index3, index4;

if (dim1 == 0) {

index1 = idx1;

} else {

index1 = i;

if (dim2 == 1) {

index2 = idx2;

} else {

index2 = j;

if (dim3 == 2) {

index3 = idx3;

} else {

index3 = k;

if (dim3 == 3) {

index4 = idx3;

} else {

index4 = k;

cout << *((a + index1 * 8 + index2 * 4 + index3 * 2) + index4) << " ";
}

cout << "]";

cout << "]" << endl;

int main() {

// Array declaration

int a[2][2][2][2];

// Function call to take input for the array

inputArray(a);

// User input for slicing

int dim1, dim2, dim3, idx1, idx2, idx3;

cout << "Enter dimensions to slice (0, 1, or 2) and indices to slice (0 or 1) (dim1 dim2 dim3 idx1 idx2
idx3): ";

cin >> dim1 >> dim2 >> dim3 >> idx1 >> idx2 >> idx3;

// Calling the function to slice and print

sliceAndPrint((int*)a, dim1, dim2, dim3, idx1, idx2, idx3);

return 0;

Question 07:
write a c++ program that searches for a specific element in a 4d array using pointer. if is found,
replace it with a user-specified value . ensure that the program handles multiple occurence of
the elemnt correctly
Solution:
#include <iostream>

using namespace std;

void searchAndReplace(int**** arr, int size, int target, int replace) {

for (int i = 0; i < size; ++i) {

for (int j = 0; j < size; ++j) {

for (int k = 0; k < size; ++k) {

for (int l = 0; l < size; ++l) {

int temp = (*(*(*(*(arr + i) + j) + k) + l)); // Dereference variable

if (temp == target) {

*(*(*(*(arr + i) + j) + k) + l) = replace; // Dereference variable

int main() {

int size;

cout << "Enter the size of each dimension of the 4D array: ";

cin >> size;

int**** arr = new int***[size];

for (int i = 0; i < size; ++i) {

arr[i] = new int**[size];

for (int j = 0; j < size; ++j) {

arr[i][j] = new int*[size];


for (int k = 0; k < size; ++k) {

arr[i][j][k] = new int[size];

for (int l = 0; l < size; ++l) {

cout << "Enter value of arr[" << i << "][" << j << "][" << k << "][" << l << "]: ";

cin >> *(*(*(*(arr + i) + j) + k) + l);

int target, replace;

cout << "Enter the element to search for: ";

cin >> target;

cout << "Enter the value to replace with: ";

cin >> replace;

searchAndReplace(arr, size, target, replace);

cout << "4D array after replacement:\n";

for (int i = 0; i < size; ++i) {

for (int j = 0; j < size; ++j) {

for (int k = 0; k < size; ++k) {

for (int l = 0; l < size; ++l) {

cout << arr[i][j][k][l] << " ";

cout << endl;

cout << endl;

}
cout << endl;

// Deallocate memory

for (int i = 0; i < size; ++i) {

for (int j = 0; j < size; ++j) {

for (int k = 0; k < size; ++k) {

delete[] arr[i][j][k];

delete[] arr[i][j];

delete[] arr[i];

delete[] arr;

return 0;

You might also like