Ally Mkomwa

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

To study the concept of two-dimensional arrays in C, let’s break it down step by

step.

What is an array? In C programming language, an array is a collection of elements


of the same data type that are stored in contiguous memory locations. Each
element in the array can be accessed using its index value.

What is a two-dimensional array? A two-dimensional array, also known as a


matrix, is an array of arrays. It can be visualized as a table with rows and columns.
In C, a two-dimensional array is declared by specifying the number of rows and
columns it will have.

Declaring and initializing a two-dimensional array: The syntax for declaring a


two-dimensional array in C is as follows:

datatype array_name[row_size][column_size];

For example, to declare a 3x4 integer matrix named “matrix”, we would write:

int matrix[3][4];

To initialize the elements of this matrix, we can use nested loops:

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

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

matrix[i][j] = i + j;

Accessing elements in a two-dimensional array: Elements in a two-dimensional


array can be accessed using the row and column indices. The indices start from 0
and go up to (row_size - 1) and (column_size - 1), respectively. For example, to
access the element at row 1, column 2 of the “matrix” array, we would write:
int element = matrix[1][2];

Manipulating values in a two-dimensional array: We can perform various


operations on the elements of a two-dimensional array, such as assigning values,
modifying values, or performing calculations. For example, we can assign a new
value to the element at row 2, column 3 of the “matrix” array:

matrix[2][3] = 10;

Using loops with two-dimensional arrays: Loops are commonly used when
working with two-dimensional arrays to iterate over the elements. We can use
nested loops to traverse through each row and column of the array. This allows
us to perform operations on all elements or search for specific values. For
example, to print all the elements of the “matrix” array, we can use nested loops
as follows:

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

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

printf("%d ", matrix[i][j]);

printf("\n");

Example of Adding two dimension arrays


#include <stdio.h>

int main() {

// Define two matrices

int matrixD[3][3] = {{-1, 2, 9},{-14, 0, 6}, {7, 1, -1}

};

int matrixE[3][3] = {{0, 8, -3},{-1, 5, 27},{3, 0, 1}

};

// Resultant matrix to store the sum

int result[3][3];

// Adding matrices element-wise

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

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

result[i][j] = matrixD[i][j] + matrixE[i][j];

// Displaying the result

printf("Sum of the matrices:\n");

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

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

printf("%d ", result[i][j]);

printf("\n");

return 0;}
RESULTS IN CONSOLE WINDOWS

You might also like