Write a C++ program. Initialize and print a two-dimensional array using functions. Pass…
- User
Write a C++ program. Initialize and print a two-dimensional array using functions. Pass the array using pointer. Both dimensions are const values
- Assistant
Here's an example C++ program that initializes and prints a two-dimensional array using functions, and passes the array using a pointer. Both dimensions of the array are const values:
#include <iostream> // Function to initialize the 2D array void initializeArray(const int* arr, int rows, int cols) { int count = 1; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { *(arr + i * cols + j) = count++; } } } // Function to print the 2D array void printArray(const int* arr, int rows, int cols) { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { std::cout << *(arr + i * cols + j) << "\t"; } std::cout << std::endl; } } int main() { const int ROWS = 3; const int COLS = 4; // Create the 2D array int array[ROWS][COLS]; // Pass array using pointer to initialize and print initializeArray(&array[0][0], ROWS, COLS); printArray(&array[0][0], ROWS, COLS); return 0; }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.