Nothing Special   »   [go: up one dir, main page]

Arrays 1

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 38

ARRAYS

Dept. of Computer Science and Engineering


National Institute of Technology, Durgapur
West Bengal, India
ARRAYS
An array is a collection of data items, all of the same type, accessed using a common name. A one-dimensional array is like a list; A two dimensional array is like a table; The C language places
no limits on the number of dimensions in an array,
C Array is a collection of variables belongings to the same data type. We can store group of data of same data type in an array. Array might be belonging to any of the data types. Array size
must be a constant value. Always, Contiguous (adjacent) memory locations are used to store array elements in memory.
An array is a variable that can store multiple values. ... For example, if you want to store 100 integers, we can create an array for it.as int data[100];
Arrays are a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of
an array as a collection of variables of the same type.
Arrays can be of following types:
1. One dimensional (1-D) arrays or Linear arrays
2. Multi dimensional arrays
(a) Two dimensional (2-D) arrays or Matrix arrays
(b) Three dimensional arrays
1. One dimensional (1-D) arrays or Linear arrays:
In it each element is represented by a single subscript. The elements are stored in consecutive memory locations. E.g. A [1], A [2], ….., A [N].
2. Multi dimensional arrays:
(a) Two dimensional (2-D) arrays or Matrix arrays:
In it each element is represented by two subscripts. Thus a two dimensional m x n array A has m rows and n columns and contains m*n elements. It is also called matrix array because in it the
elements form a matrix. E.g. A [2] [3] has 2 rows and 3 columns and 2*3 = 6 elements.
(b) Three dimensional arrays:
In it each element is represented by three subscripts. Thus a three dimensional m x n x l array A contains m*n*l elements. E.g. A [2] [3] [2] has 2*3*2 = 12 elements.
ONE DIMENSIONAL VS TWO DIMENSIONAL
ONE DIMENSIONAL ARRAY

A one-dimensional array (or single dimension array) is a type of linear array.


Accessing its elements involves a single subscript which can either represent a row
or column index. As an example consider the C declaration int anArrayName[10];
which declares a one-dimensional array of ten integers.
An array which has only one subscript is known as one dimensional array i.e) int
arr[10].
Syntax:data_type varname[size];
An array variable must be declared before being used in a program.
The declaration must have a data type(int, float, char, double, etc.), variable name,
and subscript.
The subscript represents the size of the array. If the size is declared as 10,
programmers can store 10 elements.
An array index always starts from 0. For example, if an array variable is declared as
s[10], then it ranges from 0 to 9.
Each array element stored in a separate memory location.
TWO DIMENSIONAL ARRAY
• C programming language allows multidimensional arrays. Here is the general form of a
multidimensional array declaration −type name[size1][size2]...[sizeN];
• For example, the following declaration creates a three dimensional integer array −
• int threedim[5][10][4];
• The simplest form of multidimensional array is the two-dimensional array. A two-
dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-
dimensional integer array of size [x][y], you would write something as follows −
• type arrayName [ x ][ y ];
• Where type can be any valid C data type and arrayName will be a valid C identifier. A two-
dimensional array can be considered as a table which will have x number of rows and y
number of columns.
• The arrays we looked at were all one-dimensional, but C can create and use multi-
dimensional arrays. For example : char vowels[1][5] = { {'a', 'e', 'i', 'o', 'u'} };
• An array, which has two subscript is known as two dimensional array. By using two-
dimensional arrays, programmers can manipulate data structures.
• It has two subscripts, first one represents row and second one represents column. Subscripts
are always starts with 0.
• An array of arrays is known as 2D array. The two dimensional (2D) array in C
programming is also known as matrix. A matrix can be represented as a table of rows and
columns.
• For an array of size N×M, the rows and columns are numbered from 0 to N−1 and
columns are numbered from 0 to M−1, respectively. Any element of the array can be
accessed by arr[i][j] where 0≤i<N and 0≤j<M.
• In the computer memory, all elements are stored linearly using contiguous addresses.
Therefore, in order to store a two-dimensional matrix a, two dimensional address space must
be mapped to one-dimensional address space. In the computer's memory matrices
are stored in either Row-major order or Column-major order form.
• Let a be a two dimensional m x n array. Though a is pictured as a rectangular pattern
with m rows and n columns, it is represented in memory by a block of m*n sequential
memory locations.
• A two-dimensional array a, which contains three rows and four columns can be shown as
follows. Thus, every element in the array a is identified by an element name of the form a[ i ]
[ j ], where 'a' is the name of the array, and 'i' and 'j' are the subscripts that uniquely identify
each element in 'a'.
TWO DIMENSIONAL ARRAY
• 2D array declaration:
• The general form of a multidimensional array declaration − type name[size1][size2]...[sizeN];
• For example, the following declaration creates a three dimensional integer array int thedim[5][10][4];
• To declare a 2D array, you must specify the following:
• Row-size: Defines the number of rows
• Column-size: Defines the number of columns
• Type of array: Defines the type of elements to be stored in the array i.e. either a number, character, or other such datatype. A sample form of declaration is as
follows:
• type arr[row_size][column_size]
• A sample C array is declared as :int arr[3][5];
• So, in the same way, we can declare the 2-D array as:
• The meaning of the above representation can be understood as:
• The memory allocated to variable b is of data type int.
• The data is being represented in the form of 2 rows and 3 columns.

• 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:

• Row Major Order


• Let us consider a two dimensional array to explain how row major order way of storing elements works.
• In the case of 2D array, its elements are considered as rows and columns of a table.
• When we represent an array as int Arr[i][j], the first index of it represents the row elements and the next index represents the column elements of each row. When we store the array
elements in row major order, first we will store the elements of first row followed by second row and so on.
• Hence in the memory we can find the elements of first row followed by second row and so on.
• In memory there will not be any separation between the rows.
• We have to code in such a way that we have to count the number of elements in each row depending on its column index. But in memory all the rows and their columns will be
contiguous. Below diagram will illustrate the same for a 2D array of size 3X3 i.e.; 3 rows and 3 columns.
• Array indexes always start from 0. Hence the first element of the 2D array is at int Arr[0][0].
• This is the first row-first column element. Since it is an integer array, it occupies 4 bytes of space. Next memory space is occupied by the second element of the first row, i.e.; intArr [0]
[1] – first row-second column element. This continues till all the first row elements are occupied in the memory.
• Next it picks the second row elements and is placed in the same way as first row. This goes on till all the elements of the array are occupies the memory like below. This is how it is
placed in the memory. But seeing the memory address or the value stored in the memory we cannot predict which is the first row or second row or so.
Total size/ memory occupied by 2D array is calculated as
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
TWO DIMENSIONAL ARRAY
• Array Memory Allocation in C
• Column Major Order
• This is the opposite method of row major order of storing the elements in the memory.
• In this method all the first column elements are stored first, followed by second column elements and so on.

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;
}

You might also like