Download presentation
Presentation is loading. Please wait.
1
(Numerical Arrays of Multiple Dimensions)
2
Arrays We study arrays of more than one dimension:
These data structures are widely used in software to model tables of data, matrices, maps, relationship among the variables of a system and images of all kinds-photographic, radar, X- ray, ultrasound, infrared, and magnetic resonance. We show how to declare and reference multidimensional arrays, that is ,array with two or more dimensions.
3
Array Arrays of arrays are also called two-dimensional arrays.
If it is possible with strings, it is also possible with numerical arrays.
4
ARRAY We use two dimensions when we require two coordinates:
map coordinates, pixels on a screen, matrix representations and so on…
5
Vectors and Matrices One of the most common use of arrays in scientific or engineering applications is the translation of vectors into 1D arrays and matrices into 2D arrays. A vector V = <10,20,30,40> would be represented by an array int v[4] = {10,20,30,40}; V1 being the first element in the previous example, would be 10, represented in C by v[0]. Note that in math we start counting at 1 but in C, we start at 0. For matrices, the same approach uses 2D arrays. M21 would be translated as m[1][0].
6
Multiple Dimensions The number of subscripts used to access a particular element in an array is called the dimension of the array. An array of two dimensions will have two sizes (number of rows and number of columns), hence by multiplying the two sizes we obtain the total number of cells.
7
EXAMPLE: Suppose that we are programming a robot to place nine Christmas tree ornaments in a box ,the box has nine cushioned compartments, in a 3 x 3 grid. Mission possible
8
Two Dimensions An array of two dimensions can be represented by a grid of rows and columns. Each row is numbered like an regular array. The same for the columns. int a[3][4]; will declare an 2D array of integers with 3 rows (numbered 0-2) and 4 columns (numbered 0-3). By providing the two coordinates, we can refer to an individual cell. a[1][2]=57; will place the value 57 into the third cell of the second row.
9
Example: CS [1][ 2]=98 CS 1 2 3 98
10
Three Dimensions! It is possible to have arrays of three dimensions. These are useful for spatial coordinates. If you place multiple 2D grids on a shelf, you get the third dimension. In that case the array double x[4][3][2]; would contain 5 grids of three rows and two columns.
11
2D Array Applications Matrix addition Matrix subtraction
1D arrays can be viewed as VECTORS. Similarly, 2D arrays can be viewed as MATRICES. As such, when we are dealing with 2D arrays we really trying to manipulate Matrices including: Matrix addition Matrix subtraction Matrix multiplication Matrix transposition Matrix inversion Solving for systems of linear equations Linear transformations
12
A Simple 2D Program To travel within a 2D array we will need two travelling variables (we only needed one for 1D arrays). We usually name them i and j for historical reasons dating from the days of the Fortran programming language.
13
How to Decalre and Initialize a 2D Array?
/* PROGRAM # 80 */ /* INITIALIZE A 2D ARRAY TO NON-ZERO */ #include <stdio.h> #define row 3 #define column 3 main( ){ int i, j; /*Declare and initialize a 2D array */ int List[row][column] = { {2, 4, 6}, {8, 10, 12}, {14, 16, 18} }; /* Find out addresses */ for(i=0; i< row; i++){ for(j=0; j< column; j++) printf("%5d", &List[i][j]); puts(“”); } /* Print the matrix */ printf("%3d", List[i][j]); } }
14
Placement of a 2D array in the memory
Address Memory Array Element 8680 Row #0 2 List[0][0] 8682 4 List[0][1] 8684 6 List[0][2] 8686 Row #1 8 List[1][0] 8688 10 List[1][1] 8690 12 List[1][2] 8692 Row #2 14 List[2][0] 8694 16 List[2][1] 8696 18 List[2][2] NOTE:FIG-1 Elements of a 2D array are placed in the memory in row order.
15
Q? How to Multiply a Vector by a Scalar
16
How to Multiply a Vector by a Scalar
/* MULTIPLY VECTOR BY SCALAR *//* PROGRAM # 79 */ #include <stdio.h> #define asize 3 /*Declare functions */ void GetParameter(int list[ ], int *scalar); void PrintList(int list[ ]); void MulByScalar(int list[ ], int scalar); main( ){ int vector[asize], number; /* Input first array from the user and display it */ GetParameter(vector, &number); PrintList(vector); /* Multiply array by the scalar display the new array */ MulByScalar(vector, number); } /* To get the array from the user */ void GetParameter(int list[ ], int *scalar){ int i; puts(“please enter the scalar: “); scanf(“%d”, scalar); for(i=0; i<asize; i++){ printf("Pls enter list[%d]: ",i); scanf("%d",&list[i]);
17
/* PROGRAM # 79 */… /* To multiply a vector by a scalar*/
void MulByScalar(int list[ ], int scalar){ int i; for(i=0; i<asize; i++) list[i] *= scalar; } /* To printout the elements of the array */ void PrintList(int list[ ]){ printf("list[%d] is %d\n",i, list[i]); puts(“”);
18
Q? /* FIND MINIMUM IN AN ARRAY */
19
Finding MIN Value /* FIND MINIMUM IN AN ARRAY *//* PROGRAM # 76 */
#include <stdio.h> #define asize 8 void GetList(int list[ ]); /* Declare functions */ int MinimumValue(int list[ ]); main( ){ int vector[asize]; int index; GetList(vector); printf("The smallest number in the list is %d\n", MinimumValue(vector) ); } /* To get the array from the user */ void GetList(int list[ ]){ int i; for(i=0; i<asize; i++){ printf("Pls enter list[%d]: ",i); scanf("%d",&list[i]); /* To find the minimum */ int MinimumValue(int list[ ]){ int i, minimum; minimum = list[0]; for(i = 1; i < asize; i++) if(list[i] < minimum) minimum = list[i]; return(minimum);
20
Q? /* ADD UP TWO ARRAYS */ /* TWO ARRAYS MUST BE OF THE SAME SIZE */
21
How to Add Two Vectors? /* PROGRAM # 77 */ /* ADD UP TWO ARRAYS */
/* TWO ARRAYS MUST BE OF THE SAME SIZE */ #include <stdio.h> #define asize 3 /*Declare functions to get 2 arrays add them and print the result */ void GetList(int list[ ]); void PrintList(int list[ ]); void Add2Vector(int list1[ ], int list2[ ], int list3[ ]); main( ){ /* Declare 3 arrays */ int vector1[asize], vector2[asize], vector3[asize]; /* Call the function GetList, to input the first array from the user, and PrintList to print the array */ GetList(vector1); PrintList(vector1); /* Input second array and display it */ GetList(vector2); PrintList(vector2); /* Add elements of two arrays, display the result */ Add2Vector(vector1, vector2, vector3); PrintList(vector3); }
22
How to Add Two Vectors?... /* PROGRAM # 77 */
/* To get the array from the user */ void GetList(int list[ ]){ int i; for(i=0; i<asize; i++){ printf("Pls enter list[%d]: ",i); scanf("%d",&list[i]); } /* To add up two vectors */ void Add2Vector(int list1[ ], int list2[ ], int list3[ ]){ for(i=0; i<asize; i++) list3[i] = list1[i] + list2[i]; /* To printout the elements of the array */ void PrintList(int list[ ]){ printf("list[%d] is %d\n",i, list[i]); puts(“”);
23
HOMEWORK!!! How to Add or Subtract Two Vectors?
/* ADD OR SUBTRACT TWO ARRAYS */ /* TWO ARRAYS MUST BE OF THE SAME SIZE */ /* To get the choice of the operation from the user */
24
(Numerical Arrays of Multiple Dimensions)
25
Arrays We study arrays of more than one dimension:
These data structures are widely used in software to model tables of data, matrices, maps, relationship among the variables of a system and images of all kinds-photographic, radar, X- ray, ultrasound, infrared, and magnetic resonance. We show how to declare and reference multidimensional arrays, that is ,array with two or more dimensions.
26
Traversing the Elements of a 2D Array /
Traversing the Elements of a 2D Array /* 3 METHODS OF MANIPULATING OF ELEMENTS OF A MATRIX*/ /* PROGRAM #80-B */ /* 3 METHODS OF MANIPULATING OF ELEMENTS OF A MATRIX*/ #include<stdio.h> #define row 3 #define column 3 main( ){ int Matrix[row][column]={ {1, 3, 5}, {7, 9, 11}, {13, 15, 17} }; int i, j, *ptr; int *FirstElement=&Matrix[0][0]; int *LastElement=&Matrix[row-1][column-1]; }
27
/* METHOD 1 */ /* Use of two FOR loops, the outer loop for moving along rows, */ /* the inner loop for moving along columns */ for(i = 0; i < row; i++) for( j = 0; j < column; j++) printf(“%5d”, Matrix[i][j]); puts(“”);
28
/* METHOD 2 */ /* PTR is a pointer pointing to the1st element of the matrix. This pointer gets incremented by one through the For loop */ for(ptr = FirstElement; ptr <= LastElement; ptr++) printf(“%5d”, *ptr);
29
/* METHOD 3 */ /* Showing &MATRIX[i][0] and MATRIX[i] are the same ie, any matrix is a collection of row vectors */ /* For MATRIX[i][j], vectors can be accessed using MATRIX[i] */ printf(“\n%d, %d\n”, &Matrix[0][0], &Matrix[1][0]); printf(“\n%d, %d\n”, Matrix[0], Matrix[1]); for(i = 0; i < row; i++) for( j = 0; j < column; j++) printf(“%5d”, *(Matrix[i]+j) );
30
STRINGS STRINGS IN C FUNCTIONS DEALING WITH CHARACTERS
FUNCTIONS DEALING WITH STRINGS
31
Strings There is no string type in C. Instead, to approximate strings, we will use arrays of characters. To transform a simple array of characters into a string, it must contain the '\0‘ character in the last cell. Note that '\0' is one character. It is called the null character or the end-of-string character.
32
STRINGS IN C String and array Similarities:
Both represent a collection of a fixed number of elements of the same type Elements of both array & string are located consecutively in the memory Name of the array is a pointer that points to the first element of the array Name of the string is a pointer that points to the first element of the string
33
STRINGS IN C String and array Differences:
Array represents a collection of numerical values, Data types include int, float, double String represents a collection of characters Data type include only characters
34
String & Character: Character: a byte of data (ASCII CODE)
char Letter='B'; /* Letter is a variable of data type char */ String: a collection of characters char Str[ ]="BIRDS"; /* Str is a string */ NOTE: 'A': a single character "A": a string containing 2 characters, 'A' and '\0'
35
How to Declare a String? 1. Need to have a name for the string
2. Need to know the length of the string 3. Actual memory space needed is length of the string + 1 (to take care of the NULL character) 4. Data type is char Example: char Str[20];
36
To declare a string and initialize it
we could do it the same way as seen before: char city[ ] = {'T', 'o', 'r', 'o', 'n', 't', 'o', '\0'}; Notice that the size of the array can be omitted here, since the computer can deduce it. However, declaring the size (in this case 8), is always good form. But there is a simpler way: char city[ ] = “Toronto”; If you specify the size here, do not forget the invisible '\0'! Size must be 8 not 7! The result is exactly the same. By using the simpler way, the '\0' is added automatically at the end. 'T' ' o' 'r' 'o' 'n' 't' 'o' '\0‘
37
“U" and ‘U' Double quotes " " represent a string, A single quote ' ', one character. ‘U' is the single character U But “U" is an array size 2 containing the ‘U' character and the '\0' character. All string constants are represented in double quotes (remember "This is my first C program." ?).
38
How to Initialize a String?
/*PROGRAM # 94*/ /*DEMONSTRATES INITIALIZING STRING*/ /* length of the string is 5, need 5+1 memory space */ /* char Str[6]=”BIRDS”; */ #include <stdio.h> main( ){ /* Declare and array with type char */ char str[ ] = "BIRDS"; printf("The string is %s.", str); } Note: The format specifier for a string variable is %s. char str [ ]="BIRDS": declare an array named str capable of storing characters initialize it to "BIRDS"
39
Inside the Memory char Str[6]=”BIRDS”; char Str[ ]=”BIRDS”;
These 2 statements are equal.
40
Memory Map – Placement of a string within the memory
Address memory Array element 2400 ‘B’ Str[0] 2401 ‘I’ Str[1] 2402 ‘R’ Str[2] 2403 ‘D’ Str[3] 2404 ‘S’ Str[4] 2405 ‘\0’ Str[5]
41
NOTES!!! Str and &str[0] both refer to the top of the string (ie, address 2400). ‘\0’ is NULL character. ‘\0’ lets ‘C’ knows where the string ends. When we calculate the length of the string, '\0' is NOT counted. The length of the string is 5 but we need 6 bytes for the string (one extra for ‘\0’). Therefore, when declaring the string we need (LengthOfString+1) bytes.
42
Inside the Memory char Str[100]="BIRDS";
is acceptable, it means that we set aside 100 bytes in the memory for Str. Right now we only initialize the first 6 bytes but we expect that later on there will be some usage for the rest of them. Furthermore, we do not have any idea about the content of the Str[6] to str[99].
43
Placement of a string within the memory
Address memory Array element 2400 ‘B’ Str[0] 2401 ‘I’ Str[1] 2402 ‘R’ Str[2] 2403 ‘D’ Str[3] 2404 ‘S’ Str[4] 2405 ‘\0’ Str[5] 2406 ? Str[6] 2407 Str[7] 2408 Str[8] …
44
/*DEMONSTRATES DISPLAYING STRING*/
/* PROGRAM # 95 */ #include <stdio.h> #define ssize 6 main( ){ char str[ ] = "BIRDS"; int i; printf("Our string is %s. \n", str); /*Display characters string contains*/ puts(“Our string is made out of the following characters:”); for(i=0; i<ssize; i++) printf("%c\n ", str[i]); puts(“”); } AFTER EXECUTION: Our string is BIRDS. Our string is made out of the following characters: B I R D S
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.