ASSIGNMENT

ASSIGNMENT
Q.1 What is Array ? Explain 2D array with example?
Answer :-
An array in programming is a collection of elements, all of the same data type, stored in contiguous memory locations.
Arrays provide a way to store multiple values under a single variable name, making it easier to handle large datasets.
Each element in an array can be accessed using an index.
For example, in C++, an array of integers can be declared as
int arr[5]; // Declares an array of 5 integers
Here, `arr[0]` refers to the first element, `arr[1]` to the second, and so on.
A 2D array (two-dimensional array) is an array of arrays. It is a grid-like structure where data is arranged in rows and columns.
Each element in a 2D array is accessed using two indices:
The first index specifies the row.
The second index specifies the column.
This is useful for representing tabular data, such as matrices or tables.
Declaring a 2D Array in C++.
The syntax for declaring a 2D array is:
data_type array_name[rows][columns];
Example :-
int matrix[3][4]; // A 2D array with 3 rows and 4 columns
Accessing Elements in a 2D Array
array_name[row_index][column_index];
Example :-
matrix[1][2] = 7; // Assigns the value 7 to the element at row 1, column 2
#include <iostream>
using namespace std;
int main() {
// Declare and initialize a 2D array
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// Display the elements of the 2D array
cout << “Elements of the 2D array are:” << endl;
for (int i = 0; i < 3; i++) { // Loop through rows
for (int j = 0; j < 4; j++) { // Loop through columns
cout << matrix[i][j] << ” “; // Access each element
}
cout << endl; // Move to the next row
}
// Access a specific element
int row = 2, column = 3;
cout << “Element at row ” << row << “, column ” << column << “: ”
<< matrix[row – 1][column – 1] << endl; // Output 11
return 0;
}
Key Points:
A 2D array organizes data into rows and columns, making it ideal for problems involving grids or tables.
Nested loops are often used to process elements of a 2D array.
The number of rows and columns must be defined at the time of array declaration.