Chapter 8
Introduction to Two Dimensional Arrays
Definition: A two-dimensional array is a data structure that organizes data in rows and columns.
Accessing Elements: To access an element, specify the array name followed by the row and column offsets.
Structure of Two Dimensional Arrays
Declaration Syntax: The declaration requires specifying the row size and column size.
Example:
int data[ROWS][COLUMNS];
Memory Allocation: Allocates a consecutive block of memory: (row size) * (column size).
Initialization of Two Dimensional Arrays
Initialization Syntax: Values can be initialized directly during declaration.
Example:
cpp int counts[COUNTRIES][MEDALS] = { {1, 0, 1}, {1, 1, 0}, {0, 0, 1}, {1, 0, 0}, {0, 1, 1}, {0, 1, 1}, {1, 1, 0} };
Accessing and Assigning Values:
Example for accessing value:
int value = counts[3][1];Example for assigning value:
counts[3][1] = 8;
Inputting Values into 2D Arrays
Using Nested Loops: Nested for loops are typically used for inputting values.
Example:
cpp for (int i = 0; i < RSIZE; ++i) for (int j = 0; j < CSIZE; ++j) v[i][j] = i + j;
Operations on Two Dimensional Arrays
Computing Averages:
Average of all elements:
cpp double sum = 0, average; for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) sum += array[i][j]; average = sum / (n * m);Average of a specific row:
cpp double rowAverage = 0; for (int j = 0; j < c; ++j) rowAverage += array[i][j]; rowAverage /= c;Average of a specific column:
cpp double colAverage = 0; for (int i = 0; i < r; ++i) colAverage += array[i][j]; colAverage /= r;
Outputting 2D Arrays
Printing Format: Use nested for loops to print arrays row by row, with whitespaces between elements.
Example:
cpp for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) std::cout << array[i][j] << ' '; std::cout << std::endl; }
Passing 2D Arrays to Functions
By Reference: 2D arrays can be passed to functions by reference, specifying the column dimension as a constant.
Function Prototype:
int rowAverage(int Arr[][COLSIZE], int whichRow);Example Invocation:
avg = rowAverage(table, 3);
Matrix Theory Related to 2D Arrays
Matrix Definition: A matrix is a rectangular set of numbers, represented as a 2D array.
Basic Operations: Include matrix addition, subtraction, multiplication, and finding determinants.
Matrix multiplication is defined when the number of columns in the first matrix equals the number of rows in the second matrix.
Example Code for Matrix Multiplication
void matrixMult(int a[][N], int b[][N], int c[][N]) {
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
c[i][j] = 0;
for (int k = 0; k < N; ++k) {
c[i][j] += a[i][k] * b[k][j];
}
}
}
}
Practical Programming Examples
Complete Program for Medal Counts: The complete program reads data for countries' medal counts and computes totals. A sample output demonstrates how to format and display this data.
Conclusion
Essential Aspects of 2D Arrays: Understanding their declaration, initialization, operations, and use in matrix computations is crucial for effective engineering programming in C++.
More detailed version
Introduction to Two Dimensional Arrays
Two-dimensional arrays (2D arrays) are essential data structures in programming that effectively organize and manage large datasets in a grid format consisting of rows and columns. They are widely used in various applications, especially in engineering and scientific computations. Understanding 2D arrays is critical for effective programming in languages like C++.
Definition
A two-dimensional array is a data structure that organizes data in rows and columns, essentially resembling a matrix form. Each element in the 2D array can be accessed using two indices: one for the row and one for the column.
Accessing Elements
To access an element within a 2D array, specify the array name followed by the row and column indices in square brackets. For example, to access the element in the 2nd row and 3rd column, you would use array[1][2] (considering 0-based indexing).
Structure of Two Dimensional Arrays
Declaration Syntax
The declaration requires specifying both the number of rows and columns. For instance, to declare a 2D array of integers, the syntax is as follows:
int data[ROWS][COLUMNS];
With ROWS and COLUMNS being predefined constants or integers that specify the dimensions of the array.
Memory Allocation
A 2D array allocates memory in a consecutive block, where the total size is determined by multiplying the row size by the column size:
Total Memory Size = (row size) * (column size). This contiguous allocation makes access and manipulations faster compared to fragmented memory.
Initialization of Two Dimensional Arrays
Initialization Syntax
2D arrays can be initialized directly during their declaration to enhance clarity and reduce the need for separate input statements. A typical example in C++ looks like this:
int counts[COUNTRIES][MEDALS] = { {1, 0, 1}, {1, 1, 0}, {0, 0, 1}, {1, 0, 0}, {0, 1, 1}, {0, 1, 1}, {1, 1, 0} };
Here, COUNTRIES and MEDALS are constants that define the number of countries and the types of medals, respectively.
Accessing and Assigning Values
You can access a specific value in a 2D array, like so:
int value = counts[3][1];
This retrieves the value from the 4th row and 2nd column.
Similarly, assigning a value can be shown as:
counts[3][1] = 8;
This sets the element in the 4th row and 2nd column to 8.
Inputting Values into 2D Arrays
For inputting elements into a 2D array, nested loops are typically utilized. This approach allows for systematic traversal of each row and column. An example implementation is:
for (int i = 0; i < RSIZE; ++i)
for (int j = 0; j < CSIZE; ++j)
v[i][j] = i + j;
This code initializes each element in the array v with the sum of its row and column indices, effectively filling the array with computed values.
Operations on Two Dimensional Arrays
Computing Averages
You can calculate the average of all the elements in a 2D array, or specific rows and columns:
Average of all elements:
double sum = 0, average;
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j)
sum += array[i][j];
average = sum / (n * m);
Average of a specific row:
double rowAverage = 0;
for (int j = 0; j < c; ++j)
rowAverage += array[i][j];
rowAverage /= c;
Average of a specific column:
double colAverage = 0;
for (int i = 0; i < r; ++i)
colAverage += array[i][j];
colAverage /= r;
These code snippets illustrate how to traverse a 2D array and perform summation to compute averages.
Outputting 2D Arrays
Printing a 2D array involves presenting its contents in a readable format, often using nested loops:
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j)
std::cout << array[i][j] << ' ';
std::cout << std::endl;
}
This code prints each row on a new line, with spaces separating the elements for clarity.
Passing 2D Arrays to Functions
2D arrays can be passed to functions by reference, which allows the function to manipulate the original array without needing to return it. For this, specify the column dimension as a constant:
Function Prototype
int rowAverage(int Arr[][COLSIZE], int whichRow);
Example Invocation
Here’s how you can invoke the function:
avg = rowAverage(table, 3);
This example calculates the average of the 4th row from the table array.
Matrix Theory Related to 2D Arrays
Matrix Definition
A matrix, in mathematical terms, is a rectangular set of numbers that can be represented as a 2D array. Matrices are fundamental in areas like linear algebra, machine learning, and statistics.
Basic Operations
Common operations that can be performed on matrices include addition, subtraction, multiplication, and calculating determinants. Notably, matrix multiplication can only be defined when the number of columns in the first matrix matches the number of rows in the second matrix.
Example Code for Matrix Multiplication
Matrix multiplication can be implemented efficiently using nested loops, as shown below:
void matrixMult(int a[][N], int b[][N], int c[][N]) {
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
c[i][j] = 0;
for (int k = 0; k < N; ++k) {
c[i][j] += a[i][k] * b[k][j];
}
}
}
}
This implementation multiplies two matrices a and b, and stores the result in matrix c.
Practical Programming Examples
A complete program can be developed to read data for countries' medal counts, compute totals, and format the output accordingly. Such practical applications highlight the utility of 2D arrays in real-world programming scenarios.
Conclusion
Mastering the essential aspects of 2D arrays—including their declaration, initialization, operations, and applications in matrix computations—is crucial for efficient programming and data manipulation in languages like C++. Developing a solid understanding of these concepts will greatly enhance one’s programming skills and ability to tackle complex problems effectively.