Introduction to Arrays  An array is used to process a collection of data of the same type  Examples: A list of names A list of temperatures  Why do we need arrays?  Imagine keeping track of 100 test scores or 1000 in memory  How would you name all the variables?  How would you process each of the variables? Array in C 2 Prepared by : Er. Rhishav Poudyal
 An array is a collection of elements of the same type that are referenced by a common name.  Compared to the basic data type (int, float & char) it is an aggregate or derived data type.  All the elements of an array occupy a set of contiguous memory locations.  Consider the following issue: "We have a list of 1000 students' marks of an integer type. If using the basic data type (int), we will declare something like the following…" int studMark0, studMark1, studMark2, ..., studMark999;
 Can you imagine how long we have to write the declaration part by using normal variable declaration? int main(void) { int studMark1, studMark2, studMark3, studMark4, …, …, studMark998, stuMark999, studMark1000; … … return 0; }
Definition and Initialization  Array is defined as the user defined (derived) data type which hold multiple data having same kind of data type.  An array is defined using a declaration statement. data_type array_name[size];  allocates memory for size elements  subscript of first element is 0  subscript of last element is size-1  size must be a constant 5 Array in C Prepared by : Er. Rhishav Poudyal
Definition – Array  A collection of objects of the same type stored contiguously in memory under one name  May be type of any kind of variable  May even be collection of arrays!  For ease of access to any member of array  For passing to functions as a group 6 Array in C Prepared by : Er. Rhishav Poudyal
Initializing Arrays  To initialize an array when it is declared  The values for the indexed variables are enclosed in braces and separated by commas  Example: int children[3] = { 2, 12, 1 }; Is equivalent to: int children[3]; children[0] = 2; children[1] = 12; children[2] = 1; Array in C 7 Prepared by : Er. Rhishav Poudyal
One-Dimensional Arrays  Suppose, you need to store years of 100 cars. Will you define 100 variables? int y1, y2,…, y100;  An array is an indexed data structure to represent several variables having the same data type: int y[100]; 8 y[0] y[1] y[2] … y[k-1] y[k] y[k+1] … y[98] y[99] Array in C Prepared by : Er. Rhishav Poudyal
Arrays  Array  Group of consecutive memory locations  Same name and type  To refer to an element, specify  Array name  Position number  Format: arrayname[ position number ]  First element at position 0  n element array named c:  c[ 0 ], c[ 1 ]...c[ n – 1 ] 9 Array in C Prepared by : Er. Rhishav Poudyal
One-Dimensional Arrays (cont’d)  An element of an array is accessed using the array name and an index or subscript, for example: y[5] which can be used like a variable  In C, the subscripts always start with 0 and increment by 1, so y[5] is the sixth element  The name of the array is the address of the first element and the subscript is the offset 10 y[0] y[1] y[2] … y[k-1] y[k] y[k+1] … y[98] y[99] Array in C Prepared by : Er. Rhishav Poudyal
Arrays  Array elements are like normal variables c[ 0 ] = 3; printf( "%d", c[ 0 ] );  Perform operations in subscript. If x equals 3 c[ 5 - 2 ] == c[ 3 ] == c[ x ] 11 Array in C Prepared by : Er. Rhishav Poudyal
Declaring Arrays  When declaring arrays, specify  Name  Type of array  Number of elements arrayType arrayName[ numberOfElements ];  Examples: int c[ 10 ]; float myArray[ 3284 ];  Declaring multiple arrays of same type  Format similar to regular variables  Example: int b[ 100 ], x[ 27 ]; 12 Array in C Prepared by : Er. Rhishav Poudyal
Examples (continued)  int C[]  An array of an unknown number of integers (allowable in a parameter of a function)  C[0], C[1], …, C[max-1]  int D[10][20]  An array of ten rows, each of which is an array of twenty integers  D[0][0], D[0][1], …, D[1][0], D[1][1], …, D[9][19]  Not used so often as arrays of pointers 13 Array in C Prepared by : Er. Rhishav Poudyal
Examples (continued)  Initializers int n[ 5 ] = { 1, 2, 3, 4, 5 };  If not enough initializers, rightmost elements become 0 int n[ 5 ] = { 0 }  All elements 0  If too many a syntax error is produced syntax error  C arrays have no bounds checking  If size omitted, initializers determine it int n[ ] = { 1, 2, 3, 4, 5 };  5 initializers, therefore 5 element array 14 Array in C Prepared by : Er. Rhishav Poudyal
Declaring an Array  An array, named score, containing five variables of type int can be declared as int score[ 5 ];  This is like declaring 5 variables of type int: score[0], score[1], … , score[4]  The value in brackets is called  A subscript  An index Array in C 15 Prepared by : Er. Rhishav Poudyal
Assigning values to an array 16 For loops are often used to assign values to an array Example: int list[5], i; for(i=0; i<5; i++){ list[i] = i; } list[0] list[3] list[4] list[1] list[2] 0 1 2 3 4 list[0] list[1] list[2] list[3] list[4] OR for(i=0; i<=4; i++){ list[i] = i; } Array in C Prepared by : Er. Rhishav Poudyal
Assigning values to an array 17 Give a for loop to assign the below values to list int list[5], i; for(i=0; i<5; i++){ list[i] = 4-i; } list[0] list[3] list[4] list[1] list[2] 4 3 2 1 0 Array in C Prepared by : Er. Rhishav Poudyal
Array Element  May be used wherever a variable of the same type may be used  In an expression (including arguments)  On left side of assignment  Examples:– A[3] = x + y; x = y – A[3]; z = sin(A[i]) + cos(B[j]); 18 Array in C Prepared by : Er. Rhishav Poudyal
Array Elements (continued)  Generic form:–  ArrayName[integer-expression]  ArrayName[integer-expression] [integer-expression]  Same type as the underlying type of the array  Definition:– Array Index – the expression between the square brackets 19 Array in C Prepared by : Er. Rhishav Poudyal
Array Elements (continued)  Array elements are commonly used in loops  E.g., for(i=0; i < max; i++) A[i] = i*i; sum = 0; for(j=0; j < max; j++) sum += B[j]; 20 Array in C Prepared by : Er. Rhishav Poudyal
Array Initialization  int A[5] = {2, 4, 8, 16, 32};  Static or automatic  int B[20] = {2, 4, 8, 16, 32};  Unspecified elements are guaranteed to be zero  int C[4] = {2, 4, 8, 16, 32};  Error — compiler detects too many initial values  int D[5] = {2*n, 4*n, 8*n, 16*n, 32*n};  Automatically only; array initialized to expressions 21 Array in C Prepared by : Er. Rhishav Poudyal
Implicit Array Size Determination  int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};  Array is created with as many elements as initial values  In this case, 12 elements  Values must be compile-time constants (for static arrays)  Values may be run-time expressions (for automatic arrays) 22 Array in C Prepared by : Er. Rhishav Poudyal
Caution! Caution! Caution!  It is the programmer’s responsibility to avoid indexing off the end of an array  Likely to corrupt data  May cause a segmentation fault  Could expose system to a security hole!  C does NOT check array bounds  I.e., whether index points to an element within the array  Might be high (beyond the end) or negative (before the array starts) 23 Array in C Prepared by : Er. Rhishav Poudyal
Initializing Arrays  Arrays can be initialized at the time they are declared. Examples: double taxrate[3] ={0.15, 0.25, 0.3}; char list[5] = {‘h’, ’e’, ’l’, ’l’, ’o’}; double vector[100] = {0.0}; /* assigns zero to all 100 elements */ int s[] = {5,0,-5}; /*the size of s is 3*/ 24 Array in C Prepared by : Er. Rhishav Poudyal
Find Maximum  Find maximum value in data array int data[100], max, i; for (i=0; i<100; i++) scanf(“%d”,&data[i]); max = data[0]; for (i=1; i<100; i++){ if (data[i] > max) max = data[i]; } printf("Max = %dn",max); 26 Array in C Prepared by : Er. Rhishav Poudyal
Find average 27  Find average of values in data array int data[100], sum, i, avg; for (i=0; i<100; i++) data[i] = rand_int(10,109); sum = 0; for (i=0; i<100; i++) { sum = sum + data[i]; } avg = (double)sum/100; printf(“Avg = %lfn", avg); Array in C Prepared by : Er. Rhishav Poudyal
Number of elements greater than average  After finding the average as shown in previous slide, use the following code 28 count = 0; for (i=0; i<100; i++) { if (data[i] > avg) count++; } printf(“%d elements are greater than avg”, count); Array in C Prepared by : Er. Rhishav Poudyal
Copy array1 to array2 in reverse order 29 6 3 1 9 7 2 0 2 1 3 4 5 2 7 9 1 3 6 array1 array2 Array in C Prepared by : Er. Rhishav Poudyal
What are Multidimensional Arrays  A multidimensional array is treated as an array of arrays.  Let a be a k-dimensional array; the elements of a can be accessed using the following syntax: a [ i1 ] [ i2 ]…[ ik ] where i1, i2, ….., ik Array in C 30 Prepared by : Er. Rhishav Poudyal
Multidimensional Arrays  Applying what we learned about simple arrays to multidimensional array, we get the following: A k-dimensional array can be created with either of the following methods:  Using the new operator  Using the k-dimensional initializer Array in C 31 Prepared by : Er. Rhishav Poudyal
Creating k-dimensional Array Using the new operator new Type [ n1] [n2]…[nk]  Size of each dimension is n1, n2, …,nk, respectively.  All the elements in the array are initialized to default initial values based on the type of the elements  Using k-dimensional array initializer {I1, I2, ...., Ik}  where each I1, I2, ...., Ik is a (k-1)- dimensional array initializer. Array in C 32 Prepared by : Er. Rhishav Poudyal
Examples…  Using the new operator, the following example is of creating and initializing a two-dimensional array. double mat1[4 ][5 ] This creates a 4 x 5 two- dimensional array. All elements are initialized to 0.0.  Using k-dimensional array initializer, the following example is of creating and initializing a two-dimensional array. int mat2[ ] [ ] = {{1, 2, 3}, {4, 5, 6}}; This creates a 2 x 3 two-dimensional array. The elements are initialized as: mat2[0][0]=1 mat2[1][0]= 4 mat2[0][1]=2 mat2[1][1]= 5 mat2[0][2]=3 mat2[1][2]= 6 Array in C 33 Prepared by : Er. Rhishav Poudyal
Two Dimensional Arrays  A two dimensional array stores data as a logical collection of rows and columns.  Each element of a two-dimensional array has a row position and a column position.  To access an element in a two-dimensional array, you must specify the name of the array followed by:  a row offset  a column offset Array in C 34 Prepared by : Er. Rhishav Poudyal
Declaration and Initialization  The declaration of a two-dimensional array requires a row size and a column size.  All array elements must be of the same type.  Elements accessed by two offsets – a row offset and a column offset.  The name of the array holds the address of the first byte of memory Array in C 35 Prepared by : Er. Rhishav Poudyal
Example //Declaration int data[2][3]; Memory Snapshot ? ? ? ? ? ? data Array in C 36 Prepared by : Er. Rhishav Poudyal
Example //Declaration int data[2][3]; ? ? ? ? ? ? row 0 row 1 col 0 col 1 col 2 row/column form: Array in C 37 Prepared by : Er. Rhishav Poudyal
2D Array Definition Syntax Syntax: data_type identifier[ [row_size] ][column_size] [= initialization_list ]; //row_size and column_size must be integer constants Examples int data[2][5]; //allocates consecutive memory for 10 integer values double t[2][2] = {{3.0,5.0},{2.1,7.2}}; //allocates and initializes Array in C 38 Prepared by : Er. Rhishav Poudyal
Initialization Examples int temp[4][3] = {50, 70, 60, 48, 75, 62, 51, 69, 60, 52, 78, 63}; int temp[4][3] = {{50, 70, 60}, {48, 75, 62}, {51, 69, 60}, {52, 78, 63}}; int temp[][3] = {{50, 70, 60}, {48, 75, 62}, {51, 69, 60}, {52, 78, 63}}; int temp[][3] = {50, 70, 60, 48, 75, 62, 51, 69, 60, 52, 78, 63}; Array in C 39 Prepared by : Er. Rhishav Poudyal
Example: Input  Nested for loops are often used when inputting and assigning values to a two-dimensional array.  Nested loops are generally useful for getting around the 2D arrays… //Declaration double table[RSIZE][CSIZE]; for (int i=0; i<RSIZE; ++i) //every row for (int j=0; j<CSIZE; ++j )//every col scanf(“%lf”,&table[i][j]; Array in C 40 Prepared by : Er. Rhishav Poudyal
Example: Assignment //Declaration const int RSIZE(3),CSIZE(2); double v[RSIZE][CSIZE]; for (int i=0; i<RSIZE; ++i) //every row for (int j=0; j<CSIZE; ++j )//every col v[i][j] = i+j; 0 1 1 2 2 3 V Array in C 41 Prepared by : Er. Rhishav Poudyal
Example: Computations  Compute the average value of an array with n rows and m columns. double sum(0), average; for (int i=0; i<n; ++i)//every row for (int j=0; j<m; ++j )//every col sum += array[i][j]; average = sum / (n*m); Array in C 42 Prepared by : Er. Rhishav Poudyal
Example: Computations  Compute the average value of the nth row of a 2D array with r rows and c columns. double sum(0), rowAverage; for (int j=0; j<c; ++j ) //every col sum += array[n][j]; average = sum / c; Array in C 43 Prepared by : Er. Rhishav Poudyal
Outputting 2D Arrays  Two dimensional arrays are often printed in a row by row format, using nested for statements.  When printing the row values of an array, be sure to print:  whitespace between the values in a row.  a newline character at the end of each row. Array in C 44 Prepared by : Er. Rhishav Poudyal
Example: Printing for (int i=0; i<n; ++i) {//every row { for (int j=0; j<m; ++j )//every col printf(“%d”,array[i][j]); } Array in C 45 Prepared by : Er. Rhishav Poudyal
Matrix  A matrix is a set of numbers arranged in a rectangular grid with rows and columns.  A square matrix has the same number of rows as columns.  Row and Column offsets in Matrices are 1-based.  2D Arrays are useful for representing matrices. Array in C 46 Prepared by : Er. Rhishav Poudyal
Matrix Computations and Operations  The determinant of a matrix is a scalar value used in computing matrix inverses and solving systems of simultaneous equations.  The transpose of a matrix is a new matrix in which the rows of the original matrix are the columns of the transpose.  Matrices of the same size may be added or subtracted element-by-element.  Matrix multiplication (M * N) is defined only when the number of columns of M is equal to the number of rows in N.  Result has the size rows(M) x cols(N) Array in C 47 Prepared by : Er. Rhishav Poudyal
C program to store temperature of two cities for a week and display it. 48 Array in C Prepared by : Er. Rhishav Poudyal
49 const int CITY = 2; const int WEEK = 7; void main() { int temperature[CITY][WEEK]; for (int i = 0; i < CITY; ++i) { for(int j = 0; j < WEEK; ++j) { printf("City %d, Day %d: ", i+1, j+1); scanf("%d", &temperature[i][j]); } } printf("nDisplaying values: nn"); for (int i = 0; i < CITY; ++i) { for(int j = 0; j < WEEK; ++j) { printf("City %d, Day %d = %dn", i+1, j+1, temperature[i][j]); } } } Array in C Prepared by : Er. Rhishav Poudyal
WAP to find the sum of two matrices of order 2*2 . 50 Array in C Prepared by : Er. Rhishav Poudyal
51 #include <stdio.h> int main() { float a[2][2], b[2][2], c[2][2]; int i, j; printf("Enter elements of 1st matrixn"); for(i=0; i<2; ++i) for(j=0; j<2; ++j) { printf("Enter a%d%d: ", i+1, j+1); scanf("%f", &a[i][j]); } printf("Enter elements of 2nd matrixn"); for(i=0; i<2; ++i) for(j=0; j<2; ++j) { printf("Enter b%d%d: ", i+1, j+1); scanf("%f", &b[i][j]); } Array in C Prepared by : Er. Rhishav Poudyal
52 // adding corresponding elements of two arrays for(i=0; i<2; ++i) for(j=0; j<2; ++j) { c[i][j] = a[i][j] + b[i][j]; } // Displaying the sum printf("nSum Of Matrix:"); for(i=0; i<2; ++i) for(j=0; j<2; ++j) { printf("%.1ft", c[i][j]); if(j==1) printf("n"); } return 0; } Array in C Prepared by : Er. Rhishav Poudyal
WAP to Find Transpose of a Matrix 53 Array in C Prepared by : Er. Rhishav Poudyal
54 #include <stdio.h> void main() { int a[10][10], transpose[10][10], row, col, i, j; printf("Enter rows and columns of matrix: "); scanf("%d %d", &row, &col); printf("nEnter elements of matrix:n"); for(i=0; i<row; ++i) for(j=0; j<col; ++j) { printf("Enter element a%d%d: ",i+1, j+1); scanf("%d", &a[i][j]); } Array in C Prepared by : Er. Rhishav Poudyal
55 // Finding the transpose of matrix a for(i=0; i<row; ++i) for(j=0; j<col; ++j) { transpose[j][i] = a[i][j]; } // Displaying the transpose of matrix a printf("nTranspose of Matrix:n"); for(i=0; i<col; ++i) for(j=0; j<row; ++j) { printf("%d ",transpose[i][j]); if(j==r-1) printf("nn"); } } Array in C Prepared by : Er. Rhishav Poudyal
Program to Multiply Two Matrices 56 Array in C Prepared by : Er. Rhishav Poudyal
57 #include <stdio.h> int main() { int a[10][10], b[10][10], result[10][10], r1, c1, r2, c2, i, j, k; printf("Enter rows and column for first matrix: "); scanf("%d %d", &r1, &c1); printf("Enter rows and column for second matrix: "); scanf("%d %d",&r2, &c2); // Column of first matrix should be equal to row of second matrix and if (c1 != r2) { printf("Error! column of first matrix not equal to row of second.nn"); } Array in C Prepared by : Er. Rhishav Poudyal
58 // elements of first matrix. printf("nEnter elements of matrix 1:n"); for(i=0; i<r1; ++i) for(j=0; j<c1; ++j) { printf("Enter elements a%d%d: ",i+1, j+1); scanf("%d", &a[i][j]); } // elements of second matrix. printf("nEnter elements of matrix 2:n"); for(i=0; i<r2; ++i) for(j=0; j<c2; ++j) { printf("Enter elements b%d%d: ",i+1, j+1); scanf("%d",&b[i][j]); } Array in C Prepared by : Er. Rhishav Poudyal
59 // Initializing all elements of result matrix to 0 for(i=0; i<r1; ++i) for(j=0; j<c2; ++j) { result[i][j] = 0; } // Multiplying matrices a and b and // storing result in result matrix for(i=0; i<r1; ++i) for(j=0; j<c2; ++j) for(k=0; k<c1; ++k) { result[i][j]+=a[i][k]*b[k][j]; } Array in C Prepared by : Er. Rhishav Poudyal
60 // Displaying the result printf("nOutput Matrix:n"); for(i=0; i<r1; ++i) for(j=0; j<c2; ++j) { printf("%d ", result[i][j]); if(j == c2-1) printf("nn"); } return 0; } Array in C Prepared by : Er. Rhishav Poudyal

Array and its operation in C programming

  • 2.
    Introduction to Arrays An array is used to process a collection of data of the same type  Examples: A list of names A list of temperatures  Why do we need arrays?  Imagine keeping track of 100 test scores or 1000 in memory  How would you name all the variables?  How would you process each of the variables? Array in C 2 Prepared by : Er. Rhishav Poudyal
  • 3.
     An arrayis a collection of elements of the same type that are referenced by a common name.  Compared to the basic data type (int, float & char) it is an aggregate or derived data type.  All the elements of an array occupy a set of contiguous memory locations.  Consider the following issue: "We have a list of 1000 students' marks of an integer type. If using the basic data type (int), we will declare something like the following…" int studMark0, studMark1, studMark2, ..., studMark999;
  • 4.
     Can youimagine how long we have to write the declaration part by using normal variable declaration? int main(void) { int studMark1, studMark2, studMark3, studMark4, …, …, studMark998, stuMark999, studMark1000; … … return 0; }
  • 5.
    Definition and Initialization Array is defined as the user defined (derived) data type which hold multiple data having same kind of data type.  An array is defined using a declaration statement. data_type array_name[size];  allocates memory for size elements  subscript of first element is 0  subscript of last element is size-1  size must be a constant 5 Array in C Prepared by : Er. Rhishav Poudyal
  • 6.
    Definition – Array A collection of objects of the same type stored contiguously in memory under one name  May be type of any kind of variable  May even be collection of arrays!  For ease of access to any member of array  For passing to functions as a group 6 Array in C Prepared by : Er. Rhishav Poudyal
  • 7.
    Initializing Arrays  Toinitialize an array when it is declared  The values for the indexed variables are enclosed in braces and separated by commas  Example: int children[3] = { 2, 12, 1 }; Is equivalent to: int children[3]; children[0] = 2; children[1] = 12; children[2] = 1; Array in C 7 Prepared by : Er. Rhishav Poudyal
  • 8.
    One-Dimensional Arrays  Suppose,you need to store years of 100 cars. Will you define 100 variables? int y1, y2,…, y100;  An array is an indexed data structure to represent several variables having the same data type: int y[100]; 8 y[0] y[1] y[2] … y[k-1] y[k] y[k+1] … y[98] y[99] Array in C Prepared by : Er. Rhishav Poudyal
  • 9.
    Arrays  Array  Groupof consecutive memory locations  Same name and type  To refer to an element, specify  Array name  Position number  Format: arrayname[ position number ]  First element at position 0  n element array named c:  c[ 0 ], c[ 1 ]...c[ n – 1 ] 9 Array in C Prepared by : Er. Rhishav Poudyal
  • 10.
    One-Dimensional Arrays (cont’d) An element of an array is accessed using the array name and an index or subscript, for example: y[5] which can be used like a variable  In C, the subscripts always start with 0 and increment by 1, so y[5] is the sixth element  The name of the array is the address of the first element and the subscript is the offset 10 y[0] y[1] y[2] … y[k-1] y[k] y[k+1] … y[98] y[99] Array in C Prepared by : Er. Rhishav Poudyal
  • 11.
    Arrays  Array elementsare like normal variables c[ 0 ] = 3; printf( "%d", c[ 0 ] );  Perform operations in subscript. If x equals 3 c[ 5 - 2 ] == c[ 3 ] == c[ x ] 11 Array in C Prepared by : Er. Rhishav Poudyal
  • 12.
    Declaring Arrays  Whendeclaring arrays, specify  Name  Type of array  Number of elements arrayType arrayName[ numberOfElements ];  Examples: int c[ 10 ]; float myArray[ 3284 ];  Declaring multiple arrays of same type  Format similar to regular variables  Example: int b[ 100 ], x[ 27 ]; 12 Array in C Prepared by : Er. Rhishav Poudyal
  • 13.
    Examples (continued)  intC[]  An array of an unknown number of integers (allowable in a parameter of a function)  C[0], C[1], …, C[max-1]  int D[10][20]  An array of ten rows, each of which is an array of twenty integers  D[0][0], D[0][1], …, D[1][0], D[1][1], …, D[9][19]  Not used so often as arrays of pointers 13 Array in C Prepared by : Er. Rhishav Poudyal
  • 14.
    Examples (continued)  Initializers intn[ 5 ] = { 1, 2, 3, 4, 5 };  If not enough initializers, rightmost elements become 0 int n[ 5 ] = { 0 }  All elements 0  If too many a syntax error is produced syntax error  C arrays have no bounds checking  If size omitted, initializers determine it int n[ ] = { 1, 2, 3, 4, 5 };  5 initializers, therefore 5 element array 14 Array in C Prepared by : Er. Rhishav Poudyal
  • 15.
    Declaring an Array An array, named score, containing five variables of type int can be declared as int score[ 5 ];  This is like declaring 5 variables of type int: score[0], score[1], … , score[4]  The value in brackets is called  A subscript  An index Array in C 15 Prepared by : Er. Rhishav Poudyal
  • 16.
    Assigning values toan array 16 For loops are often used to assign values to an array Example: int list[5], i; for(i=0; i<5; i++){ list[i] = i; } list[0] list[3] list[4] list[1] list[2] 0 1 2 3 4 list[0] list[1] list[2] list[3] list[4] OR for(i=0; i<=4; i++){ list[i] = i; } Array in C Prepared by : Er. Rhishav Poudyal
  • 17.
    Assigning values toan array 17 Give a for loop to assign the below values to list int list[5], i; for(i=0; i<5; i++){ list[i] = 4-i; } list[0] list[3] list[4] list[1] list[2] 4 3 2 1 0 Array in C Prepared by : Er. Rhishav Poudyal
  • 18.
    Array Element  Maybe used wherever a variable of the same type may be used  In an expression (including arguments)  On left side of assignment  Examples:– A[3] = x + y; x = y – A[3]; z = sin(A[i]) + cos(B[j]); 18 Array in C Prepared by : Er. Rhishav Poudyal
  • 19.
    Array Elements (continued) Generic form:–  ArrayName[integer-expression]  ArrayName[integer-expression] [integer-expression]  Same type as the underlying type of the array  Definition:– Array Index – the expression between the square brackets 19 Array in C Prepared by : Er. Rhishav Poudyal
  • 20.
    Array Elements (continued) Array elements are commonly used in loops  E.g., for(i=0; i < max; i++) A[i] = i*i; sum = 0; for(j=0; j < max; j++) sum += B[j]; 20 Array in C Prepared by : Er. Rhishav Poudyal
  • 21.
    Array Initialization  intA[5] = {2, 4, 8, 16, 32};  Static or automatic  int B[20] = {2, 4, 8, 16, 32};  Unspecified elements are guaranteed to be zero  int C[4] = {2, 4, 8, 16, 32};  Error — compiler detects too many initial values  int D[5] = {2*n, 4*n, 8*n, 16*n, 32*n};  Automatically only; array initialized to expressions 21 Array in C Prepared by : Er. Rhishav Poudyal
  • 22.
    Implicit Array SizeDetermination  int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};  Array is created with as many elements as initial values  In this case, 12 elements  Values must be compile-time constants (for static arrays)  Values may be run-time expressions (for automatic arrays) 22 Array in C Prepared by : Er. Rhishav Poudyal
  • 23.
    Caution! Caution! Caution! It is the programmer’s responsibility to avoid indexing off the end of an array  Likely to corrupt data  May cause a segmentation fault  Could expose system to a security hole!  C does NOT check array bounds  I.e., whether index points to an element within the array  Might be high (beyond the end) or negative (before the array starts) 23 Array in C Prepared by : Er. Rhishav Poudyal
  • 24.
    Initializing Arrays  Arrayscan be initialized at the time they are declared. Examples: double taxrate[3] ={0.15, 0.25, 0.3}; char list[5] = {‘h’, ’e’, ’l’, ’l’, ’o’}; double vector[100] = {0.0}; /* assigns zero to all 100 elements */ int s[] = {5,0,-5}; /*the size of s is 3*/ 24 Array in C Prepared by : Er. Rhishav Poudyal
  • 26.
    Find Maximum  Findmaximum value in data array int data[100], max, i; for (i=0; i<100; i++) scanf(“%d”,&data[i]); max = data[0]; for (i=1; i<100; i++){ if (data[i] > max) max = data[i]; } printf("Max = %dn",max); 26 Array in C Prepared by : Er. Rhishav Poudyal
  • 27.
    Find average 27  Findaverage of values in data array int data[100], sum, i, avg; for (i=0; i<100; i++) data[i] = rand_int(10,109); sum = 0; for (i=0; i<100; i++) { sum = sum + data[i]; } avg = (double)sum/100; printf(“Avg = %lfn", avg); Array in C Prepared by : Er. Rhishav Poudyal
  • 28.
    Number of elementsgreater than average  After finding the average as shown in previous slide, use the following code 28 count = 0; for (i=0; i<100; i++) { if (data[i] > avg) count++; } printf(“%d elements are greater than avg”, count); Array in C Prepared by : Er. Rhishav Poudyal
  • 29.
    Copy array1 toarray2 in reverse order 29 6 3 1 9 7 2 0 2 1 3 4 5 2 7 9 1 3 6 array1 array2 Array in C Prepared by : Er. Rhishav Poudyal
  • 30.
    What are Multidimensional Arrays A multidimensional array is treated as an array of arrays.  Let a be a k-dimensional array; the elements of a can be accessed using the following syntax: a [ i1 ] [ i2 ]…[ ik ] where i1, i2, ….., ik Array in C 30 Prepared by : Er. Rhishav Poudyal
  • 31.
    Multidimensional Arrays  Applyingwhat we learned about simple arrays to multidimensional array, we get the following: A k-dimensional array can be created with either of the following methods:  Using the new operator  Using the k-dimensional initializer Array in C 31 Prepared by : Er. Rhishav Poudyal
  • 32.
    Creating k-dimensional Array Usingthe new operator new Type [ n1] [n2]…[nk]  Size of each dimension is n1, n2, …,nk, respectively.  All the elements in the array are initialized to default initial values based on the type of the elements  Using k-dimensional array initializer {I1, I2, ...., Ik}  where each I1, I2, ...., Ik is a (k-1)- dimensional array initializer. Array in C 32 Prepared by : Er. Rhishav Poudyal
  • 33.
    Examples…  Using thenew operator, the following example is of creating and initializing a two-dimensional array. double mat1[4 ][5 ] This creates a 4 x 5 two- dimensional array. All elements are initialized to 0.0.  Using k-dimensional array initializer, the following example is of creating and initializing a two-dimensional array. int mat2[ ] [ ] = {{1, 2, 3}, {4, 5, 6}}; This creates a 2 x 3 two-dimensional array. The elements are initialized as: mat2[0][0]=1 mat2[1][0]= 4 mat2[0][1]=2 mat2[1][1]= 5 mat2[0][2]=3 mat2[1][2]= 6 Array in C 33 Prepared by : Er. Rhishav Poudyal
  • 34.
    Two Dimensional Arrays A two dimensional array stores data as a logical collection of rows and columns.  Each element of a two-dimensional array has a row position and a column position.  To access an element in a two-dimensional array, you must specify the name of the array followed by:  a row offset  a column offset Array in C 34 Prepared by : Er. Rhishav Poudyal
  • 35.
    Declaration and Initialization The declaration of a two-dimensional array requires a row size and a column size.  All array elements must be of the same type.  Elements accessed by two offsets – a row offset and a column offset.  The name of the array holds the address of the first byte of memory Array in C 35 Prepared by : Er. Rhishav Poudyal
  • 36.
  • 37.
    Example //Declaration int data[2][3]; ? ?? ? ? ? row 0 row 1 col 0 col 1 col 2 row/column form: Array in C 37 Prepared by : Er. Rhishav Poudyal
  • 38.
    2D Array DefinitionSyntax Syntax: data_type identifier[ [row_size] ][column_size] [= initialization_list ]; //row_size and column_size must be integer constants Examples int data[2][5]; //allocates consecutive memory for 10 integer values double t[2][2] = {{3.0,5.0},{2.1,7.2}}; //allocates and initializes Array in C 38 Prepared by : Er. Rhishav Poudyal
  • 39.
    Initialization Examples int temp[4][3]= {50, 70, 60, 48, 75, 62, 51, 69, 60, 52, 78, 63}; int temp[4][3] = {{50, 70, 60}, {48, 75, 62}, {51, 69, 60}, {52, 78, 63}}; int temp[][3] = {{50, 70, 60}, {48, 75, 62}, {51, 69, 60}, {52, 78, 63}}; int temp[][3] = {50, 70, 60, 48, 75, 62, 51, 69, 60, 52, 78, 63}; Array in C 39 Prepared by : Er. Rhishav Poudyal
  • 40.
    Example: Input  Nestedfor loops are often used when inputting and assigning values to a two-dimensional array.  Nested loops are generally useful for getting around the 2D arrays… //Declaration double table[RSIZE][CSIZE]; for (int i=0; i<RSIZE; ++i) //every row for (int j=0; j<CSIZE; ++j )//every col scanf(“%lf”,&table[i][j]; Array in C 40 Prepared by : Er. Rhishav Poudyal
  • 41.
    Example: Assignment //Declaration const intRSIZE(3),CSIZE(2); double v[RSIZE][CSIZE]; for (int i=0; i<RSIZE; ++i) //every row for (int j=0; j<CSIZE; ++j )//every col v[i][j] = i+j; 0 1 1 2 2 3 V Array in C 41 Prepared by : Er. Rhishav Poudyal
  • 42.
    Example: Computations  Computethe average value of an array with n rows and m columns. double sum(0), average; for (int i=0; i<n; ++i)//every row for (int j=0; j<m; ++j )//every col sum += array[i][j]; average = sum / (n*m); Array in C 42 Prepared by : Er. Rhishav Poudyal
  • 43.
    Example: Computations  Computethe average value of the nth row of a 2D array with r rows and c columns. double sum(0), rowAverage; for (int j=0; j<c; ++j ) //every col sum += array[n][j]; average = sum / c; Array in C 43 Prepared by : Er. Rhishav Poudyal
  • 44.
    Outputting 2D Arrays Two dimensional arrays are often printed in a row by row format, using nested for statements.  When printing the row values of an array, be sure to print:  whitespace between the values in a row.  a newline character at the end of each row. Array in C 44 Prepared by : Er. Rhishav Poudyal
  • 45.
    Example: Printing for (inti=0; i<n; ++i) {//every row { for (int j=0; j<m; ++j )//every col printf(“%d”,array[i][j]); } Array in C 45 Prepared by : Er. Rhishav Poudyal
  • 46.
    Matrix  A matrixis a set of numbers arranged in a rectangular grid with rows and columns.  A square matrix has the same number of rows as columns.  Row and Column offsets in Matrices are 1-based.  2D Arrays are useful for representing matrices. Array in C 46 Prepared by : Er. Rhishav Poudyal
  • 47.
    Matrix Computations and Operations The determinant of a matrix is a scalar value used in computing matrix inverses and solving systems of simultaneous equations.  The transpose of a matrix is a new matrix in which the rows of the original matrix are the columns of the transpose.  Matrices of the same size may be added or subtracted element-by-element.  Matrix multiplication (M * N) is defined only when the number of columns of M is equal to the number of rows in N.  Result has the size rows(M) x cols(N) Array in C 47 Prepared by : Er. Rhishav Poudyal
  • 48.
    C program tostore temperature of two cities for a week and display it. 48 Array in C Prepared by : Er. Rhishav Poudyal
  • 49.
    49 const int CITY= 2; const int WEEK = 7; void main() { int temperature[CITY][WEEK]; for (int i = 0; i < CITY; ++i) { for(int j = 0; j < WEEK; ++j) { printf("City %d, Day %d: ", i+1, j+1); scanf("%d", &temperature[i][j]); } } printf("nDisplaying values: nn"); for (int i = 0; i < CITY; ++i) { for(int j = 0; j < WEEK; ++j) { printf("City %d, Day %d = %dn", i+1, j+1, temperature[i][j]); } } } Array in C Prepared by : Er. Rhishav Poudyal
  • 50.
    WAP to findthe sum of two matrices of order 2*2 . 50 Array in C Prepared by : Er. Rhishav Poudyal
  • 51.
    51 #include <stdio.h> int main() { floata[2][2], b[2][2], c[2][2]; int i, j; printf("Enter elements of 1st matrixn"); for(i=0; i<2; ++i) for(j=0; j<2; ++j) { printf("Enter a%d%d: ", i+1, j+1); scanf("%f", &a[i][j]); } printf("Enter elements of 2nd matrixn"); for(i=0; i<2; ++i) for(j=0; j<2; ++j) { printf("Enter b%d%d: ", i+1, j+1); scanf("%f", &b[i][j]); } Array in C Prepared by : Er. Rhishav Poudyal
  • 52.
    52 // adding correspondingelements of two arrays for(i=0; i<2; ++i) for(j=0; j<2; ++j) { c[i][j] = a[i][j] + b[i][j]; } // Displaying the sum printf("nSum Of Matrix:"); for(i=0; i<2; ++i) for(j=0; j<2; ++j) { printf("%.1ft", c[i][j]); if(j==1) printf("n"); } return 0; } Array in C Prepared by : Er. Rhishav Poudyal
  • 53.
    WAP to FindTranspose of a Matrix 53 Array in C Prepared by : Er. Rhishav Poudyal
  • 54.
    54 #include <stdio.h> void main() { inta[10][10], transpose[10][10], row, col, i, j; printf("Enter rows and columns of matrix: "); scanf("%d %d", &row, &col); printf("nEnter elements of matrix:n"); for(i=0; i<row; ++i) for(j=0; j<col; ++j) { printf("Enter element a%d%d: ",i+1, j+1); scanf("%d", &a[i][j]); } Array in C Prepared by : Er. Rhishav Poudyal
  • 55.
    55 // Finding thetranspose of matrix a for(i=0; i<row; ++i) for(j=0; j<col; ++j) { transpose[j][i] = a[i][j]; } // Displaying the transpose of matrix a printf("nTranspose of Matrix:n"); for(i=0; i<col; ++i) for(j=0; j<row; ++j) { printf("%d ",transpose[i][j]); if(j==r-1) printf("nn"); } } Array in C Prepared by : Er. Rhishav Poudyal
  • 56.
    Program to MultiplyTwo Matrices 56 Array in C Prepared by : Er. Rhishav Poudyal
  • 57.
    57 #include <stdio.h> int main() { inta[10][10], b[10][10], result[10][10], r1, c1, r2, c2, i, j, k; printf("Enter rows and column for first matrix: "); scanf("%d %d", &r1, &c1); printf("Enter rows and column for second matrix: "); scanf("%d %d",&r2, &c2); // Column of first matrix should be equal to row of second matrix and if (c1 != r2) { printf("Error! column of first matrix not equal to row of second.nn"); } Array in C Prepared by : Er. Rhishav Poudyal
  • 58.
    58 // elements offirst matrix. printf("nEnter elements of matrix 1:n"); for(i=0; i<r1; ++i) for(j=0; j<c1; ++j) { printf("Enter elements a%d%d: ",i+1, j+1); scanf("%d", &a[i][j]); } // elements of second matrix. printf("nEnter elements of matrix 2:n"); for(i=0; i<r2; ++i) for(j=0; j<c2; ++j) { printf("Enter elements b%d%d: ",i+1, j+1); scanf("%d",&b[i][j]); } Array in C Prepared by : Er. Rhishav Poudyal
  • 59.
    59 // Initializing allelements of result matrix to 0 for(i=0; i<r1; ++i) for(j=0; j<c2; ++j) { result[i][j] = 0; } // Multiplying matrices a and b and // storing result in result matrix for(i=0; i<r1; ++i) for(j=0; j<c2; ++j) for(k=0; k<c1; ++k) { result[i][j]+=a[i][k]*b[k][j]; } Array in C Prepared by : Er. Rhishav Poudyal
  • 60.
    60 // Displaying theresult printf("nOutput Matrix:n"); for(i=0; i<r1; ++i) for(j=0; j<c2; ++j) { printf("%d ", result[i][j]); if(j == c2-1) printf("nn"); } return 0; } Array in C Prepared by : Er. Rhishav Poudyal