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 reference
- Assistant
Here is an example of a C++ program that initializes and prints a two-dimensional array using functions and passing the array by reference:
cpp#include <iostream> void initializeArray(int (&arr)[3][3]) { int count = 1; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { arr[i][j] = count++; } } } void printArray(const int (&arr)[3][3]) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { std::cout << arr[i][j] << " "; } std::cout << std::endl; } } int main() { int array[3][3]; initializeArray(array); printArray(array); return 0; }In this program, the
initializeArrayfunction takes a two-dimensional array as a reference parameter and initializes it with values from 1 to 9. The function also takes the two-dimensional array as a reference parameter and prints its values. - User
Now make rows and columns a const values
- Assistant
Sure! Here's an updated version of the program where the number of rows and columns are constant values:
cpp#include <iostream> const int ROWS = 3; const int COLS = 3; void initializeArray(int (&arr)[ROWS][COLS]) { int count = 1; for (int i = 0; i < ROWS; i++) { for (int j = 0; j < COLS; j++) { arr[i][j] = count++; } } } void printArray(const int (&arr)[ROWS][COLS]) { for (int i = 0; i < ROWS; i++) { for (int j = 0; j < COLS; j++) { std::cout << arr[i][j] << " "; } std::cout << std::endl; } } int main() { int array[ROWS][COLS]; initializeArray(array); printArray(array); return 0; }In this updated version, the and variables are declared as constant values using the keyword. These values are used to define the size of the two-dimensional array and are also passed as arguments to the and functions.
- User
Now pass the array using pointer
- Assistant
Here's an example program where the two-dimensional array is passed using a pointer instead of a reference:
cpp#include <iostream> const int ROWS = 3; const int COLS = 3; void initializeArray(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++; } } } 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) << " "; } std::cout << std::endl; } } int main() { int array[ROWS][COLS]; initializeArray((int *)array, ROWS, COLS); printArray((int *)array, ROWS, COLS); return 0; }