Arrays 1
Arrays 1
Arrays 1
• The data inside the array can be accessed through the above representation.
• In 2-D arrays representation, the first square bracket represents the number of rows, and the second one is for the number of columns. The index
representation of the array for the first element always starts with zero and ends with size-1. Array variable (here b) always holds the base address of the
memory block and is called an internal pointer variable.
• So, for example, if the number of rows is 3, then the index representation for accessing the data in rows will be 0, 1 and 2. The same logic applies to the
column indexes too. For the above representation, to get the data of the 2nd row 3rd column, we can access by b[1][2].
TWO DIMENSIONAL ARRAY
• INITIALIZATION OF A 2D ARRAY INITIALIZATION OF A 2D ARRAY
• To initialize a two-dimensional array, it is easiest to use nested Things that you must consider while initializing a 2D array
braces, with each set of numbers representing a row: We already know, when we initialize a normal array (or you can say one
• Although some compilers will let you omit the inner braces, we dimensional array) during declaration, we need not to specify the size of it.
highly recommend you include them anyway, both for However that’s not the case with 2D array, you must always specify the
readability purposes and because of the way that C++ will second dimension even if you are specifying elements during the declaration.
replace missing initializers with 0. Let’s understand this with the help of few examples –
/* Valid declaration*/ int abc[2][2] = {1, 2, 3 ,4 }
int array[3][5]
/* Valid declaration*/ int abc[][2] = {1, 2, 3 ,4 }
{ /* Invalid declaration – you must specify second dimension*/
{ 1, 2, 3, 4, 5 }, // row 0 int abc[][] = {1, 2, 3 ,4 }
{ 6, 7, 8, 9, 10 }, // row 1 /* Invalid because of the same reason mentioned above*/
{ 11, 12, 13, 14, 15 } // row 2
}; int abc[2][] = {1, 2, 3 ,4 }
Multidimensional arrays may be initialized by specifying
bracketed values for each row. Following is an array with 3 rows
int array[3][5] and each row has 4 columns int a[3][4] =
{ { {0, 1, 2, 3} , /* initializers for row indexed by 0 */
{ 1, 2 }, // row 0 = 1, 2, 0, 0, 0 {4, 5, 6, 7} , /* initializers for row indexed by 1 */
{ 6, 7, 8 }, // row 1 = 6, 7, 8, 0, 0 {8, 9, 10, 11} /* initializers for row indexed by 2 */ };
};
{ 11, 12, 13, 14 } // row 2 = 11, 12, 13, 14, 0
The nested braces, which indicate the intended row, are optional.
The following initialization is equivalent to the previous example −
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
• Two-dimensional arrays with initializer lists can omit (only) the
Different ways to initialize two-dimensional array
leftmost length specification:
int c[2][3] = {{1, 3, 0}, {-1, 5, 9}}; int c[][3] = {{1, 3, 0}, {-1, 5, 9}};
int c[2][3] = {1, 3, 0, -1, 5, 9};
There are two ways to initialize a two Dimensional arrays during
declaration.
int disp[2][4] = { {10, 11, 12, 13}, {14, 15, 16, 17} };
OR
int disp[2][4] = { 10, 11, 12, 13, 14, 15, 16, 17};
TWO DIMENSIONAL ARRAY
• Processing 2D arrays:
• The most basic form of processing is to lo op over the array and print all its elements, which can be done as follows:
type arr[row_size][column_size] = {{elements}, {elements} ... } A C example of looping over the array and printing all its
for i from 0 to row_size elements is as follows:
for j from 0 to column_size #include <stdio.h>
print arr[i][j]
int main()
• An element in a two-dimensional array is accessed by using the subscripts, { // Array declaration and initialization
• i.e., row index and column index of the array. For example − int val = a[2][3]; int arr[3][5] = {{5, 12, 17, 9, 3}, {13, 4, 8, 14, 1}, {9, 6, 3, 7,
• The above statement will take the 4th element from the 3rd row of the array. 21}};
• Let us check the program
•
// Iterate over the array
where we have used a nested loop to handle a two-dimensional array −
for(int i=0; i<3; i++)
• Accessing elements in a two-dimensional array {
• Accessing all of the elements of a two-dimensional array requires two loops: for(int j=0; j<5; j++)
• one for the row, and one for the column. { // Print out each element
• Since two-dimensional arrays are typically accessed row by row, printf("a[%d][%d] = %d\n", i,j, arr[i][j] );
• the row index is typically used as the outer loop.
} // Print new line character after the row is printed in above
1 for (int row= 0 ; row < numRows; ++row) // step through the rows in the array loop
2 { printf(“/n”);
3 for (int col=0 ; col < numCols; ++col) // step through each element in the row
4 { }
5 printf("a[%d][%d] = %d\n", i,jarray[row][col]); return 0;
6 }
7 }
TWO DIMENSIONAL ARRAY
• Array Memory Allocation in C
• In the case of multidimensional array, we have elements in the form of rows and columns. Here also memories allocated to the array are contiguous. But the elements assigned to the
memory location depend on the two different methods:
Total size/ memory occupied by 2D array is calculated as in the same way as above.
Total memory allocated to 2D Array = Number of elements * size of one element
= Number of Rows * Number of Columns * Size of one element
Total memory allocated to an Integer Array of size MXN = Number of elements * size of one element
=M Rows* N Columns * 4 Bytes
= 10*10 * 4 bytes = 400 Bytes, where M =N = 10
= 500*5 *4 bytes= 10000 Bytes, where M=500 and N= 5
Total memory allocated to an character Array of N elements= Number of elements * size of one element
= M Rows* N Columns * 1 Byte
= 10*10 * 1 Byte = 100 Bytes, where N = 10
= 500*5 * 1 Byte = 2500 Bytes, where M=500 and N= 5
• If an array is 3D or multidimensional array, then the method of allocating memory is either row major or column major order.
• Whichever is the method, memory allocated for the whole array is contiguous and its elements will occupy them in the order we choose – row major or column major.
• The total size of the array is the total number of elements * size of one element.
TWO DIMENSIONAL ARRAY
• Array Memory Allocation in C #include<stdio.h>
int main(){
• How to store user input data into 2D array /* 2D array declaration*/
int abc[5][4];
• We can calculate how many elements a two dimensional array can have by using this formula: /*Counter variables for the loop*/
• The array arr[n1][n2] can have n1*n2 elements. int i, j;
• The array that we have in the example below is having the dimensions 5 and 4. for(i=0; i<5; i++) {
• These dimensions are known as subscripts. So this array has first subscript value as 5 and second subscript value as 4. for(j=0;j<4;j++) {
• So the array abc[5][4] can have 5*4 = 20 elements. printf("Enter value for abc[%d][%d]:", i, j);
• To store the elements entered by user we are using two for loops, scanf("%d", &abc[i][j]);
}
• One of them is a nested loop. The outer loop runs from 0 to the (first subscript -1) }
• And the inner for loops runs from 0 to the (second subscript -1). return 0;
• This way the the order in which user enters the elements would be abc[0][0], abc[0][1], abc[0][2]…so on. }
• In above example, we have a 2D array abc of integer type. Conceptually we can visualize the above array like this
However the actual representation of this array in memory would be something like this:
:
TWO DIMENSIONAL ARRAY
C program to find the sum of two matrices of order 2*2 C Program to read a matrix and find sum, product of all elements of two
dimensional (matrix) array
#include <stdio.h>
int main() #include <stdio.h>
{ #define MAXROW 10
float a[2][2], b[2][2], result[2][2]; #define MAXCOL 10
// Taking input using nested for loop int main()
printf("Enter elements of 1st matrix\n"); {
for (int i = 0; i < 2; ++i) int matrix[MAXROW][MAXCOL];
for (int j = 0; j < 2; ++j) int i,j,r,c;
{ int sum,product;
printf("Enter a%d%d: ", i + 1, j + 1); printf("Enter number of Rows :");
scanf("%f", &a[i][j]); scanf("%d",&r);
} printf("Enter number of Cols :");
// Taking input using nested for loop scanf("%d",&c);
printf("Enter elements of 2nd matrix\n"); printf("\nEnter matrix elements :\n");
for (int i = 0; i < 2; ++i) for(i=0;i< r;i++)
for (int j = 0; j < 2; ++j) {
{ for(j=0;j< c;j++)
printf("Enter b%d%d: ", i + 1, j + 1); {
scanf("%f", &b[i][j]); printf("Enter element [%d,%d] : ",i+1,j+1);
} scanf("%d",&matrix[i][j]);
// adding corresponding elements of two arrays }
for (int i = 0; i < 2; ++i) }
for (int j = 0; j < 2; ++j) /*sum and product of all elements*/
{ /*initializing sun and product variables*/
result[i][j] = a[i][j] + b[i][j]; sum =0;
} product =1;
// Displaying the sum for(i=0;i< r;i++)
printf("\nSum Of Matrix:"); {
for (int i = 0; i < 2; ++i) for(j=0;j< c;j++)
for (int j = 0; j < 2; ++j) {
{ sum += matrix[i][j];
printf("%.1f\t", result[i][j]); product *= matrix[i][j];
if (j == 1) }
printf("\n");
} }
return 0; printf("\nSUM of all elements : %d \nProduct of all elements :%d",sum,product);
} return 0;
TWO DIMENSIONAL ARRAY
• Program to multiply two matrices in C language printf("\nEnter elements of matrix a: \n");
readMatrix(a,r1,c1);
printf("Enter number of Rows of matrix b: ");
#include <stdio.h> scanf("%d",&r2);
#define MAXROW 10 printf("Enter number of Cols of matrix b: ");
#define MAXCOL 10 scanf("%d",&c2);
/*User Define Function to Read Matrix*/ printf("\nEnter elements of matrix b: \n");
void readMatrix(int m[][MAXCOL],int row,int col) readMatrix(b,r2,c2);
{ if(r1==c2)
int i,j;
for(i=0;i< row;i++) {
{ /*Multiplication of two matrices*/
for(j=0;j< col;j++) for(i=0;i< r1;i++)
{ {
printf("Enter element [%d,%d] : ",i+1,j+1); for(j=0;j< c1;j++)
scanf("%d",&m[i][j]); {
} sum=0;
} for(k=0;k< r1;k++)
} {
/*User Define Function to Read Matrix*/ sum=sum + (a[i][k]*b[k][j]);
void printMatrix(int m[][MAXCOL],int row,int col) }
{ result[i][j]=sum;
int i,j; }
for(i=0;i< row;i++) }
{
for(j=0;j< col;j++) /*print matrix*/
{ printf("\nMatrix after multiplying elements (result matrix):\n");
printf("%d\t",m[i][j]); printMatrix(result,r1,c1);
}
printf("\n");
} }
} else
int main() {
{ printf("\nMultiplication can not be done.");
int a[MAXROW][MAXCOL],b[MAXROW][MAXCOL],result[MAXROW][MAXCOL]; }
int i,j,r1,c1,r2,c2;
int sum,k;
printf("Enter number of Rows of matrix a: "); return 0;
scanf("%d",&r1); }
printf("Enter number of Cols of matrix a: ");
scanf("%d",&c1);
TWO DIMENSIONAL ARRAY
#include <stdio.h>
• C program to transpose a matrix
#define MAXROW 10
#define MAXCOL 10
int main()
{
int matrix[MAXROW][MAXCOL];
int i,j,r,c;
printf("Enter number of Rows :");
scanf("%d",&r);
printf("Enter number of Cols :");
scanf("%d",&c);
printf("\nEnter matrix elements :\n");
for(i=0;i< r;i++)
{
for(j=0;j< c;j++)
{
printf("Enter element [%d,%d] : ",i+1,j+1);
scanf("%d",&matrix[i][j]);
}
}
/*Transpose a matrix */
printf("\nTranspose Matrix is :");
for(i=0;i< c;i++)
{
for(j=0;j< r;j++)
{
printf("%d\t",matrix[j][i]); /*print elements*/
}
printf("\n"); /*after each row print new line*/
}
return 0;
}