2D Array Matrix
Multiplication
Two-Dimensional (2D) Arrays in C
A two-dimensional array or 2D array is the
simplest form of the multidimensional array. We
can visualize a two-dimensional array as one-
dimensional arrays stacked vertically forming a
table with ‘m’ rows and ‘n’ columns. In C, arrays
are 0-indexed, so the row number ranges from 0
to (m-1) and the column number ranges from 0
to (n-1).
Initialization of 2D Arrays
We can initialize a 2D array by using a list of values
enclosed inside ‘{ }’ and separated by a comma as shown
in the example below:
int arr[3][2] = { 0, 1 ,2 ,3 ,4 , 5 }
or
int arr[3][2] = { {0, 1,} , { 2 , 3 } , { 4 , 5 } };
The elements will be stored in the array from left to right
and top to bottom. So, the first 2 elements from the left
will be filled in the first row, the next 2 elements in the
second row, and so on. This is clearly shown in the
second syntax where each set of inner braces represents
Declaration of 2D Array
A 2D array with m rows and n columns can be created as : type
arr_name[m][n];
Where ,
type : Type of data to be stored in each element.
arr_name : Name assigned to the array.
m : Number of rows.
n : Number of columns.
Example of 2D Array
The below example demonstrates the row – by – row traversal of a 2D array.
#include<stdio.h>
int main ( ) {
output :
int arr [3] [2] = { { 0 , 1 } , { 2 , 3} , { 4 , 5 } } ; arr [ 0 ] [ 0 ] : 0
for ( int i = 0 ; i < 3 ; i++) { arr [ 0 ] [ 1 ] : 1
for ( int j = 0 ; j < 2 ; j++) { arr [ 2 ] [ 0 ] : 2
printf (“arr[ %d] [%d] : %d “, i , j , arr [ i ] [ j ] ) ; arr [ 1 ] [ 1 ] : 3
} arr [ 2 ] [ 0 ] : 4
printf (“\n”) ; arr [ 2 ] [ 1 ] : 5
MATRIX
MULTIPLICATION
Matrix Multiplication in C
A matrix is a collection of numbers
o rg a n i z e d i n ro w s a n d c o l u m n s ,
re p re s e n t e d b y a t w o - d i m e n s i o n a l
a rr a y i n C . M a t r i c e s c a n e i t h e r b e
s q u a re o r re c t a n g u l a r. I n t h i s
a r t i c l e , w e w i l l l e a rn t h e
multiplication of two matrices in
t h e C p ro g r a m m i n g l a n g u a g e .
Example :
Input :
mat[ ] [ ] = { { 1 , 2 },
{3,4}}
mat[ ] [ ] = { { 5 , 6 }
{7,8}
Multiplication of two matrices :
{ { 1*5 + 2*7 1*6 + 2*8},
{ 3*5 + 4*7 3*6 + 4*8} }
Example : #include <stdio.h>
int main() {
int A[2][2], B[2][2], C[2][2]
int i, j, k;
printf("Enter elements of 2x2 Matrix A:\n");
for(i = 0; i < 2; i++) {
for(j = 0; j < 2; j++) {
printf("A[%d][%d]: ", i, j);
scanf("%d", &A[i][j]);
printf("Enter elements of 2x2 Matrix B:\n");
for(i = 0; i < 2; i++) {
For ( i = 0 ; i < 2 ; i++ ) {
for ( j = 0 ; j < 2 ; j++) { INPUT :
C[i][j]=0; Matrix A : 1 2
for ( k = 0 ; k < 2 ; k++ ) { 3 4
C [ i ] [ j ] += A [ i ] [ k ] * B [ k ] [ j ] ; Matrix B : 5 6
} 7 8
printf ( “ Resultant Matrix ( A × B ) : \n “ ) ; OUTPUT :
for ( i = 0 ; i < 2 ; i++ ) { Resultant Matrix ( A *
B):
for ( j = 0 ; j < 2 ; j++ ) {
19 22
THANK
YOU