Arrays An array is a collection of two or more adjacent memory cells, called array elements. Array is derived data type that is used to represent collection of data items. C Array is a collection of data belongings to the same data type. Syntax data_type array_name[array_size]; Here size is called index number or subscript. The complete set of values is referred to as any array the individual elements are called elements. Array might be belonging to any of the data types. Array size must be a constant value. Example for C Arrays: int a[5]; char b[10]; // integer array // character array i.e. string An array is collection of items stored at continuous memory locations. In other words adjacent memory locations are used to store the elements. Here, int[5] specifies that we can store five different values of same type. 1
The amount of storage is required for holding the elements that is based up on its size and size. Array elements are stored sequentially in separate locations. The lowest address corresponds to first element and the highest address corresponds to last element. The size and type of arrays cannot be changed after its declaration. An array is a collection of data that holds fixed number of values of same type. For example: if you want to store marks of 100 students, you can create an array for it. Types of C-Arrays float marks[100]; There are 2 types of C arrays. They are, One dimensional array Two dimensional array One dimensional array: It is used to represent and store data in a linear form. Array having only one subscript variable is called one dimensional array. It is called as single dimensional or linear array. Size indicates the maximum number of elements that can be stored inside the array. The collection of data can be stored under a variable name using only one subscript. Array Declaration: The general form of array declaration is : data_type array_name[array_size]; 2
For example : if we want to represent a set of five numbers 25, 35, 45, 55, 65, by array variable number, then we may declare the variable number as follows example: int a[5]; The computer reserves five storage locations as shown C Array declaration tells to compiler Type of array Name of array Number of dimensions No of elements in each dimensions 3
ARRAY INITIALIZATION OR INITIALIZATION OF AN ARRAY 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 runtime. We should assign set of values to array element before executing the program i.e at compilation time. Compile time initialization of array elements is same as ordinary variable initialization. The general form of initialization of array is, type array-name[size] = list of values ; Here list of values are separated by commas. Example int marks[4]= 67, 87, 56, 77 ; //integer array initialization float area[5]= 23.4, 6.8, 5.5 ; //float array initialization int marks[4]= 67, 87, 56, 77, 59 ; //Compile time error One important thing to remember is that when you will give more initializer(array elements) than declared array size than the compiler will give an error. #include<stdio.h> #include<conio.h> void main( ) int i; int arr[]=2,3,4; //Compile time array initialization for(i=0 ; i<3 ; i++) printf("%d\t",arr[i]); getch(); // Program to find the average of n (n < 10) numbers using arrays 4
#include <stdio.h> int main() int marks[10], i, n, sum = 0, average; printf("enter n: "); scanf("%d", &n); for(i=0; i<n; ++i) printf("enter number%d: ",i+1); scanf("%d", &marks[i]); sum += marks[i]; average = sum/n; printf("average = %d", average); return 0; Array declaration, initialization and accessing Array declaration syntax: data_type arr_name [arr_size]; Array initialization syntax: data_type arr_name [arr_size]=(value1, value2, value3,.); Array accessing syntax: arr_name[index]; Example Integer array example: int age [5]; int age[5]=0, 1, 2, 3, 4; age[0]; /*0 is accessed*/ age[1]; /*1 is accessed*/ age[2]; /*2 is accessed*/ Character array example: char str[10]; char str[10]= H, a, i ; (or) char str[0] = H ; char str[1] = a ; char str[2] = i; 5
ACCESSING ARRAY ELEMENTS An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example double salary = balance[9]; 1. We all know that array elements are randomly accessed using the subscript variable. 2. Array can be accessed using array-name and subscript variable written inside pair of square brackets []. GENERATING A POINTERS TO AN ARRAY When an array is declared, compiler allocates sufficient amount of memory to contain all the elements of the array. Base address i.e address of the first element of the array is also allocated by the compiler. Suppose we declare an array arr, int arr[5]= 1, 2, 3, 4, 5 ; Assuming that the base address of arr is 1000 and each integer requires two bytes, the five elements will be stored as follows: Here variable arr will give the base address, which is a constant pointer pointing to the element, arr[0]. Therefore arr is containing the address of arr[0] i.e 1000. 6
In short, arr has two purpose - it is the name of an array and it acts as a pointer pointing towards the first element in the array. arr is equal to &arr[0] //by default We can use a pointer to point to an Array, and then we can use that pointer to access the array. We can declare a pointer of type int to point to the array arr. int *p; p = arr; or p = &arr[0]; //both the statements are equivalent. Now we can access every element of array arr using p++ to move from one element to another. In this program, we have a pointer ptr that points to the 0 th element of the array. Similarly, we can also declare a pointer that can point to whole array instead of only one element of the array. This pointer is useful when talking about multidimensional arrays. #include<stdio.h> int main() int arr[5] = 1, 2, 3, 4, 5 ; int *ptr = arr; prinf("%p\n", ptr); return 0; 7
The pointer *ptr will print all the values stored in the array one by one. We can also use the Base address (a in above case) to act as pointer and print all the values of address. PASSING A SINGLE DIMENSION ARRAYS TO FUNCTIONS Just like variables, array can also be passed to function as an argument. In C programming, a single array element or an entire array can be passed to a function. This can be done for both one-dimensional array and a multi-dimensional array. Array elements can be passed to function by calling function that is called call by value or pass by value. Call by value: if we pass values of variables to the called function then function are called call by value. Single element of an array can be passed in similar manner as passing variable to a function. If you want to pass a single-dimension array as an argument in a function, you would have to declare a formal parameter in one of following three ways. 8
Way-1 Formal parameters as a pointer void myfunction(int *param)... Way-2 Formal parameters as a sized array void myfunction(int param[10])... Way-3 Formal parameters as an unsized array void myfunction(int param[ ])... Passing an entire one-dimensional array to a function While passing arrays as arguments to the function, only the name of the array is passed (,i.e, starting address of memory area is passed as argument). C program to pass an array containing age of person to a function. This function should find average age and display the average age in main function. 9
STRING String is sequence of characters that is treated as a single data item. Remember that c- language does not support strings as data type. In c the string is terminated by a null character \0. A String is actually one dimensional array of characters in c- language. Strings can store multiple characters, i.e. alphabets, numbers, symbols, punctuation marks, and whitespace, unlike character data type which stores only a single character. Strings are often enclosed in quotation marks. Since strings can store numbers and other symbols as well, quotation marks help the compiler to distinguish whether the data is number or text. Character constants are enclosed in single quotes. String constants are enclosed in double quotes. The null is the first ASCII character which has value of zero. Each character occupies one byte memory and last character is always \0. \0 is called null character. \0 and zero are not same because ASCII value of \0 is 0 where as ASCII value of is 48. 10
ASCII is indicates the end of the string and %s is control specifier for string. DECLARATION OF STRING Strings can be declaration at the time of declaration The string of array can be declared as follows Syntax Char data type string_variable[size]; INITIALIZATION OF STRING Strings can be initialized at the time of declaration. In c, strings can be initialized in different ways. Char ch [ ]= abcd ; Or Char ch [ 5]= abcd ; Or Char ch [ ]= a, b, c, d, \0 ; Or Char ch [ 5]= a, b, c, d, \0 ; String can be initialized using pointers Char *c= abcd ; DIFFERENT TYPES OF STRING Strcpy(s1, s2 ) : this function is used to copy the one string into another string. Strlen( s1, s2) : this function is used to finds the length of the strings. Strcat( s1,s2) : this function is used to Concatenates string s2 onto the end of string s1. Strcmp( s1,s2) : this function is used to returns an integer result. Strrev(s1,s2): reverses all characters in as string. 11
12
13
TWO DIMENSIONAL ARRAYS C language supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array. Both the row's and column's index begin from 0. Two dimensional array is nothing but array of arrays. A two dimensional array has two indexes i.e first index refers to the row, the second index refers to the column. Two-dimensional array is declared as follows, type array-name[row-size][column-size] ; Two dimensional array having more than one subscript that is called multi-dimensional array. Multi dimensional array is called as matrix. Example : int a[3][4]; A two-dimensional array a, which contains three rows and four columns can be shown as follows a[0][0] a[0][1] a[0][2] a[0][3] a[1][0] a[1][1] a[1][2] a[1][3] a[2][0] a[2][1] a[2][2] a[2][3] 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'. 14
INITIALIZING TWO-DIMENSIONAL ARRAYS The two dimensional array in C language is represented in the form of rows and columns, also known as matrix. It is also known as array of arrays or list of arrays. A way to initialize the two dimensional array at the time of declaration is given below. Syntax: type array-name[row-size][column-size]=set of values; Example int emp[4][3]= 10,20,30,40,50,60,70,80,90,100,110,120; First three elements will be 1 st row, Second three elements will be 2 nd row, Next three elements will be 3 rd row, Last three elements will be 4 th row. Here we divided into 3 because our column size is 3. Above set of values can be written as int emp [4][3]= 10,20,30,40,50,60,70,80,90,100,110,120; or int emp [4][3]= 10,20,30, 40,50,60, 70,80,90, 100,110,120 ; 15
Program for array initialization #include <stdio.h> int main ( ) /* an array with 5 rows and 2 columns*/ int a[5][2] = 0,0, 1,2, 2,4, 3,6,4,8; int i, j; /* output each array element's value */ for ( i = 0; i < 5; i++ ) for ( j = 0; j < 2; j++ ) printf("a[%d][%d] = %d\n", i,j, a[i][j] ); return 0; Output a[0][0]: 0 a[0][1]: 0 a[1][0]: 1 a[1][1]: 2 a[2][0]: 2 a[2][1]: 4 a[3][0]: 3 a[3][1]: 6 a[4][0]: 4 a[4][1]: 8 16
// C program to multiply two square matrices. #include <stdio.h> #define N 4 void multiply(int mat1[ ][N], int mat2[ ][N], int res[ ][N]) int i, j, k; for (i = 0; i < N; i++) for (j = 0; j < N; j++) res[i][j] = 0; for (k = 0; k < N; k++) res[i][j] += mat1[i][k]*mat2[k][j]; int main( ) int mat1[n][n] = 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4; int mat2[n][n] = 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4; int res[n][n]; // To store result int i, j; multiply(mat1, mat2, res); printf("result matrix is \n"); for (i = 0; i < N; i++) for (j = 0; j < N; j++) printf("%d ", res[i][j]); printf("\n"); return 0; 17
DECLARATION OF TWO DIMENSIONAL ARRAY An Array declaration introduces an identifier and describes its type, object, or function. A declaration is what the compiler needs to accept references to that identifier. We can declare an array in the c language in the following way. data_type array_name[size1][size2]; A simple example to declare two dimensional array is given below. int twodimen[4][3]; Here, 4 is the row number and 3 is the column number Program that accept values in 2-Dimensional 3 by 3 array and displays the sum of all the elements. void main() int arr[3][3], i, j, sum=0; /*Accepts input from the user and stores it in 2-D array*/ for(i=0;i<3;i++) for(j=0;j<3;j++) printf( \nenter the value for A[%d][%d]:,i,j); scanf( %d,&arr[i][j]); /*Calculate sum of elements in 2-D array*/ for(i=0;i<3;i++) for(j=0;j<3;j++) sum=sum+arr[i][j]; 18
/*Display the value of sum*/ printf( \nthe sum of the elements of 2-D array is %d, sum); Output Enter the value for A[0][0]: 1 Enter the value for A[0][1]: 2 Enter the value for A[0][2]: 3 Enter the value for A[1][0]: 4 Enter the value for A[1][1]: 5 Enter the value for A[1][2]: 6 Enter the value for A[2][0]: 7 Enter the value for A[2][1]: 8 Enter the value for A[2][2]: 9 The sum of the elements of 2-D array is 45 INDEXING POINTER pointer can replace indexing in many situations. Arrays are closely related to pointers in C programming but the important difference between them is that, a pointer variable takes different addresses as value whereas, in case of array it is fixed. 19
In C there is a very close connection between pointers and arrays. In fact they are more or less one and the same thing! When you declare an array as: int a[10]; we are in fact declaring a pointer a to the first element in the array. That is, a is exactly the same as &a[0]. The only difference between a and a pointer variable is that the array name is a constant pointer - you cannot change the location it points at. When you write an expression such as a[i] this is converted into a pointer expression that gives the value of the appropriate element. To be more precise, a[i] is exactly equivalent to *(a+i) i.e. the value pointed at by a + i. In the same way *(a+ 1) is the same as a[1] and so on. 1. An array's name is a constant pointer to the first element in the array that is a==&a[0] and *a==a[0]. 2. Array indexing is equivalent to pointer arithmetic - that is a+i=&a[i] and *(a+i)==a[i]. 3. In C programming, name of the array always points to address of the first element of an array. 4. In the above example, arr and &arr[0] points to the address of the first element. 5. &arr[0] is equivalent to arr 6. Since, the addresses of both are the same, the values of arr and &arr[0] are also the same. 7. arr[0] is equivalent to *arr (value of an address of the pointer) Similarly, 8. &arr[1] is equivalent to (arr + 1) AND, arr[1] is equivalent to *(arr + 1). 9. &arr[2] is equivalent to (arr + 2) AND, arr[2] is equivalent to *(arr + 2). 10. &arr[3] is equivalent to (arr + 3) AND, arr[3] is equivalent to *(arr + 3). &arr[i] is equivalent to (arr + i) AND, arr[i] is equivalent to *(arr + i). In C, you can declare an array and can use pointer to alter the data of an array. 20
Example: Program to find the sum of six numbers with arrays and pointers Output Enter 6 numbers: 2 3 4 5 3 4 Sum = 21 VARIABLE LENGTH ARRAYS In computer programming, a variable length array is called variable sized, runtime sized. ISO C99 allows variable length arrays these arrays are declared at runtime instead of compile time. Variable length arrays is a feature where we can allocate an auto array (on stack) of variable size. Note: size or subscript is a not a expression and it must be constant value. 21
The general form of variable sized array void fun(int n) int arr[n]; //... int main() fun(6); Example program for Variable sized array int main ( ) int m=2; int arr[m][m]; int i,j; for (i=0; i<m; i++) arr[i][j]=0; printf( %d,arr[i][j]); Printf( \n ); return 0; 22