1 Table of Content 1. Introduction 2. Basics of array 3. Types of Array 4. Declaring Arrays 5. Initializing an array 6. Processing an array 7. Summary Learning objectives 1. To understand the concept of an array 2. To study different types of arrays 3. To declare and initialize an array. 4. To know how to use array elements in multidimensional array.
2 1. Introduction As discussed in the previous modules, variables are used to hold data in memory. If a large number of data is to be stored, it would be tedious task to assign separate variable name and declare in the program. For example, processing the marks of 50 students in a class would require 50 different variable names. This task is impractical and tedious. In such scenario, C programming provides a facility of array. In real world, the examples are: to store a list of numbers or characters, to store student or employee names or to store marks of many students. An array is a systematic arrangement of similar objects, usually in rows and columns. An array stores 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. Many applications require processing of multiple data items having common characteristics. In such situation, it is always convenient to place a data item into an array. All the data items will share the same name. Instead of declaring individual variables, such as x0 x1,..., and x49, you declare one array variable such as numbers and use x[0],x[1], and..., x[49] to represent individual variables. A specific element in an array is accessed by an index. The array, pointer, structure, and union are derived data type in C. 1. Storing a string that contains series of characters. Like storing a name in memory. 2. Storing multiple strings. Like storing multiple names. C programming language provides the concept of arrays to help you with these scenarios. We have seen the Constants in C in the module 3. In this hierarchy there are two sub branches of C constant as shown in figure-1. 1) Primary constant. 2) Secondary constant. Note that here the array is shown in Secondary constants in the classification.
3 Figure-1: Primary and secondary constants In this module, we shall discuss the method of declaring the array, array notations, aray initialization, array accessing and their processing. 2. Basics of arrays In C language, it is possible to assign a single name to whole group of similar data. Let us consider an example of group of students whose marks are to be recorded. Let us assign a common name say x to all the data. Each element in the array can be assessed by its position within the list of items as shown in figure-2. x 55 x 1 =55 x[1]=55 95 x 2 =95 x[2]=95 64 x 3 =64 x[3]=64 79 x 4 =79 x[4]=79 63 x 5 =63 x[5]=63 Fig.-2 :(a) List of items, (b) List items with subscripted variable (c) Array representation In mathematics, a subscript is a number written to the right of variable name, slightly below the line, usually small in font. Subscript indicates the position of a particular element with respect to
4 the rest of elements. As it is impossible to display subscripted numbers on the standard computer, the numbers are enclosed in parentheses. A subscript is also known as index. In C language subscript starts at 0 rather than 1 and cannot be negative. In short, Array is a collection of variables belongings to the same data type. The group of data of same data type can store in an array. An array is a collection of same type of elements which are sheltered under a common name. An array can be visualized as a row in a table, whose each successive block can be thought of as memory bytes containing one element. Look at the figure below: An Array of five elements Element 1 Element 2 Element 3 Element 4 Element 5 Figure-3: Array of five elements An array has following properties Type- data type of array elements Location- location of first element of the array Length- number of data elements in the array. Size- length of the array times the size of an element. These arrays are also called as linear or one-dimensional array. The number of 8 bits- bytes that each element occupies depends on the type of array. If type of array is char then it means the array stores character elements. Since each character occupies one byte so elements of a character array occupy one byte each. Array belongs to any of the data types. Array size must be a constant value. Always, continuous (adjacent) memory locations are used to store array elements in memory.
5 It is a best practice to initialize an array to zero or null while declaring if we don t assign any values to array. 3. Types of C arrays: Arrays are classified according to the number of subscripts present in the list. Based on this there are 2 types of C arrays. These are, 1. One dimensional array 2. Multi dimensional array Figure-4: Types of array One dimensional array is used to represent and store data in a linear form. It has only one subscript in the variable name. It is also called as single dimensional or linear array. Many cases arrays having more than one subscript variable is used, which is known as multi-dimensional array. Such multi-dimensional array is also known as matrix. Let us now see how arrays are declared.
6 4. Declaring Arrays: Arrays must be declared before it is used in C program like normal variables. The array declaration is nothing but defining the type of the array ( e.g. int, float, char etc.), name of the array, number of subscripts (i.e. whether one or multi-dimensional) and total number of memory locations to be allocated (i.e. maximum value of each subscript.. 1. One dimensional array The general syntax of one dimensional array is shown below: Syntax: <data type-of-array> <name-of-array> [<number of elements in array>]; Data type-of-array: It is the type of elements that an array stores. If array stores character elements then type of array is char. If array stores integer elements then type of array is int. Besides these native types, if type of elements in array is structure objects then type of array becomes the structure. Name-of-array: This is the name that is given to array. It can be any string but it is usually suggested that some standard should be followed while naming arrays. At least the name should be in context with what is being stored in the array. [Number of elements]: This value in subscripts [] indicates the number of elements the array stores. For example : int a[10]; a [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] Figure-5: One dimensional array
7 Other similar declarations are: int rollno[100]; char name[20] float distance[5]; double average[]; 2. Multi dimensional array Although arrays with more than two dimensions are not commonly used, C language allow any size array to be declared. Please note that the exact limit is determined by the compiler. The general form of the multi-dimensional array is: Syntax: data_type array_name[array_size]... [array_size] Col1 Col2 Col3 Col4 Col5 Row1 a[0][0] a[0][1] a[0][2] a[0][3] a[0][4] Row2 a[1][0] a[1][1] a[1][2] a[1][3] a[1][4] Figure-6: Two dimensional array Some typical examples are: int a[3][3]; int table[2][3][4] float graph[5][5][5];
8 Let us consider the array table, which is a three dimensional array declared to contain 24 integers. The table may include data in 3-dimensions. Similarly, arrays with four, five, six dimensions and so on can be declared. 5. Initializing an array: Arrays can be initialized like ordinary variables either inside or outside the function. Arrays declared inside the function are local arrays and arrays declared outside the function are global arrays. Global arrays can be initialized when they are declared. Figure-7 shows methods of initializing arrays. Run time Initialization Initializing Array Size specifications Compile time initialization Without Size specifications Figure-7: Methods of array initialization Let us understand these methods of initialization starting with compilation time initialization of an array. Example-1: Array size specified int a[5] = { 4,1,5,8,2}; In this example, the size of array is specified as 5 in the initialization/declaration statement. Compiler will assign these 5 values to an array a.
9 Example-2: Array size unspecified int a[] = { 4,1,5,8,2}; In this example, the size of an array is not specified in the initialization/ declaration statement. Here, compiler counts the number of elements written inside the pair of braces and determines the size of array. After counting the number of elements in an array, the size of any array is considered to be 5 during the execution of the program. Such method of initialization is known as compilation time initialization. For example In the above example an array of five integers is declared. Note that since we are initializing at the time of declaration so there is no need to mention any value in the subscripts []. The size will automatically be calculated from the number of values. In this case, the size will be 5. An array can be initialized at run-time as shown in the following example. Here each element is initialized separately. #include <stdio.h> int main() { int a[5]; int i = 0; for(i=0;i<sizeof(a);i++) { a[i] = i; // Initializing each element separately } Return 0; }
10 In this example, the array is initialized after compilation and during the run-time. Here each element is initialized separately. One can use printf statement to inform user that new array element is to be entered. This will help user to have a prompt before data entry. Initializing array with a string (Method 1): Strings in C language are nothing but a series of characters followed by a null byte. So to store a string, we need an array of characters followed by a null byte. This makes the initialization of strings a bit different. Let us take a look : Since strings are nothing but a series of characters so the array containing a string will be containing characters char arr[] = {'c','o','d','e','\0'}; In the above declaration/initialization, we have initialized array with a series of character followed by a \0 (null) byte. The null byte is required as a terminating byte when string is read as a whole. Initializing array with a string (Method 2): char arr[] = "code"; Here we neither require to explicitly wrap single quotes around each character nor write a null character. The double quotes do the trick for us. For example : int a[2][3]={{2,4,6}, {-5,8,9}}; OR
11 int c[][]={{2,4,6}, {-5,8,9}}; OR int c[2][3]={ 2,4,6, -5,8,9}; After an array is declared it must be initialized. Otherwise, it will contain garbage value(any random value). An array can be initialized at either compile time or at run -time. Two dimensional arrays can be initialized in the same manner like one dimensional array. While specifying the values during initialization it is written row wise. Brace pairs are used to separate the values of one row to next. For example: int a[2][3] = { {1, 2, 3}, {3, 4, 5} }; Note that, special care be taken for defining the multi-dimensional array. 6. Processing an array The first step in processing any array or an array element is to know the method to access individual array elements. Accessing array elements In C programming, arrays can be accessed and treated like variables in C. For example: scanf("%d",&a[3]); This statement is used to obtain the 4 the element of array a[]. Here, the assumption is that the array is initialized from the 0 th element which is the first element of an array. scanf("%d",&a[i]);
12 This statement is used to get the (i+1)th the element of array a[] from the keyboard. Here, the assumption is that the array is initialized from the 0 th element which is the first element of an array. printf("%d",a[1]); This statement is used to print the 2 nd element of array a[]. Here, the assumption is that the array is initialized from the 0 th element which is the first element of an array. printf("%d",a[i]); This statement is used to print (i+1)th lement of array a[]. Here, the assumption is that the array is initialized from the 0 th element which is the first element of an array. Accessing Two-Dimensional Array Elements: Two dimensional array may be initialized and accessed just similar to one dimensiona l array. Following example demonstrates how to declare and initialize an array, printing an array with the help of two for loops.
13 Arithmetic Operations on Array: In this matrix format the arithmetic operation like addition can be performed where the matrix1 and matrix2 are being added together. In the matrix 1, there is 2 row and 2 column in which A11 defines the place of row1 and column1. Similarly for all other elements can also be designated and accessed like a11, a12, a21 and a22. This example shows how the values accessed and processed in the multi-dimensional arrays. Similar method may be adopted for subtraction of matrices. Let us consider a simple example to demonstrate arithmetic operations on two dimensional array: Array1[2][2]={{1,2},{3,4}} Array2[2][2]={{4,5},{2,4}} Here we see the example for addition of 2 by 2 matrices, here 1 is added with 4, 2 is added with 5 and so on.
14 Program for addition of two Matrices: #include <stdio.h> int main() { int a, b, i, j, M1[5][5], M2[5][5], sum[5][5]; printf("enter the number of rows and columns of matrix:\n"); scanf("%d%d", &a, &b); printf("enter the elements of matrix M1:\n"); for (i = 0; i < a; i++) for (j = 0; j < n; j++) scanf("%d", &M1[i][j]); printf("enter the elements of matrix M2:\n"); for (i = 0; i < a; i++) for (j = 0 ; j < b; j++) scanf("%d", &M2[i][j]); printf("sum of entered matrices:\n"); for (i = 0; i < a; i++) { for (j = 0 ; j < n; j++) { sum[i][j] = M1[i][j] + M2[i][j]; printf("%d\t", sum[i][j]); } printf("\n"); } return 0; } The result of the above program is shown here.
15 7. Summary An array is a systematic arrangement of similar objects, usually in rows and columns. An array stores 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 are classified according to the number of subscripts present in the list. Based on this there are 2 types of C arrays. These are, 1. One dimensional array 2. Multi dimensional array One dimensional array is used to represent and store data in a linear form. It has only one subscript in the variable name. It is also called as single dimensional or linear array. Many cases arrays having more than one subscript variable is used, which is known as multi-dimensional array. Arrays can be initialized like ordinary variables either inside or outside the function. Arrays declared inside the function are local arrays and arrays declared outside the function are global arrays. Different arithmetic operations can be performed on arrays.
16