Presentation is loading. Please wait.

Presentation is loading. Please wait.

Arrays and Strings Lecture 30. Summary of Previous Lecture In the previous lecture we have covered  Functions Prototypes Variable Scope  Pointers Introduction.

Similar presentations


Presentation on theme: "Arrays and Strings Lecture 30. Summary of Previous Lecture In the previous lecture we have covered  Functions Prototypes Variable Scope  Pointers Introduction."— Presentation transcript:

1 Arrays and Strings Lecture 30

2 Summary of Previous Lecture In the previous lecture we have covered  Functions Prototypes Variable Scope  Pointers Introduction to pointers Pointers and function parameters

3 Today’s Topics Arrays  Declaration  Initialization  Input/Output  Passing arrays to functions

4 Today’s Topics Character Strings  Representation  Declaration  Index of a char in a string  String operations  Common mistakes Summary

5 Array An array is a way of lining up objects in rows and columns so they are easier to count or multiply. The rows run from left to right. Array Row: Left to right. This array has 3 rows

6 Array The columns run from top to bottom. This array has four columns. Array Column:

7 Arrays in C Program A group of contiguous memory locations used to store a series of related values. The array name is a pointer to the first element All values have the same type Individual elements of an array are accessed via an integer index: array[index]

8 Referencing Array Elements Element indices start at 0: array[0] is the first element  We can reference array elements by using the array’s subscript. The first element has a subscript of 0. The last element in an array of length n has a subscript of n-1. When we write a program, we refer to an individual array element using indexing. To index a subscript, use the array name and the subscript in a pair of square brackets: anyArray[12];

9 Array Example

10 Declaring an Array To declare an array, we need to specify its data type, the array’s identifier and the size: type arrayName [arraySize]; The arraySize is constant Before using an array we must declare and initialize it!

11 Declaration Examples

12 Initialization at Array Definition Arrays may be initialized with a list of suitable values We can initialize fixed-length array elements when we define an array. If we initialize fewer values than the length of the array, C assigns zeroes to the remaining elements.

13 Array Initialization Examples

14 Arrays and Loops Since we can refer to individual array elements using numbered indexes, it is very common for programmers to use for loops when processing arrays. from Figure 8-5 in Forouzan & Gilberg, p. 462

15 Accessing Elements To access an array’s element, we need to provide an integer value to identify the index we want to access. We can do this using a constant: scores[0]; We can also use a variable: for(i = 0; i < 9; i++) { scoresSum += scores[i]; }

16 Inputting Values using a for Loop Once we know the length of an array, we can input values using a for loop: arrayLength = 9; for (j = 0; j < arrayLength; j++) { scanf( “ %d ”, &scores[j]); }//end for

17 Assigning Values to Individual Elements We can assign any value that reduces to an array’s data type: scores[5] = 42; scores[3] = 5 + 13; scores[8] = x + y; scores[0] = pow(7, 2);

18 Example: MonthlyRainfall Problem: using Rainfall Table input month output mean rainfall for that month

19 #include int main() { int month; int table[12] = { 30, 40, 45, 95, 130, 220, 210, 185, 135, 80, 40, 45 }; printf("Enter month: "); scanf("%d", &month); printf("Average rainfall: %d mm.\n", table[month-1]); return 0; } rainfall1.c Example… : MonthlyRainfall (v.1)

20 #include int main() { int month; int table[12] = { 30, 40, 45, 95, 130, 220, 210, 185, 135, 80, 40, 45 }; printf("Enter month: "); scanf("%d", &month); printf("Average rainfall: %d mm.\n", table[month-1]); return 0; } rainfall1.c Example (cont.): MonthlyRainfall (v.1)

21 #include #define NMONTHS 12 /* Store and print rainfall */ int main() { int data[NMONTHS]; int month; for ( month=0; month < NMONTHS; month++ ) { scanf("%d", &data[month] ); }... rainio1.c Example: IORainfall-1 using LOOP

22 #include #define NMONTHS 12 /* Store and print rainfall */ int main() { int data[NMONTHS]; int month; for ( month=0; month < NMONTHS; month++ ) { scanf("%d", &data[month] ); }... rainio1.c Example (cont): IORainfall-1 Macro: Defined NMONTHS to be 12. Later in program NMONTHS will be used

23 #include #define NMONTHS 12 /* Store and print rainfall */ int main() { int data[NMONTHS]; int month; for ( month=0; month < NMONTHS; month++ ) { scanf("%d", &data[month] ); }... rainio1.c Example (cont): IORainfall-1

24 Array 12345678910111201234567891011 Array index Values data Value at this position can be accessed through data [6]

25 #include #define NMONTHS 12... /* Print from January to December */ for ( month=0; month < NMONTHS; month++ ) { printf( "%d ", data[month] ); } printf("\n"); /* Print from December to January */ for ( month = NMONTHS - 1; month >= 0; month-- ) { printf( "%d ", data[month] ); } printf("\n"); return 0; } rainio1.c Example…..: IORainfall-2 (v.1) This will print all contents of the array data at location month Print the array in reverse order

26 #include #define NMONTHS 12... /* Print from January to December */ for ( month=0; month < NMONTHS; month++ ) { printf( "%d ", data[month] ); } printf("\n"); /* Print from December to January */ for ( month = NMONTHS - 1; month >= 0; month-- ) { printf( "%d ", data[month] ); } printf("\n"); return 0; } rainio1.c Example…..: IORainfall-2 (v.1)

27 “Copying” Arrays We cannot directly copy one array to another, even if they have the same length and share the same data type. Instead, we can use a for loop to copy values: for (m = 0; m < 25; m++) { array2[m] = array1[m]; }//end for

28 Swapping Array Elements To swap (or exchange) values, we must use a temporary variable. A common novice’s mistake is to try to assign elements to one another: /*The following is a logic error*/ numbers[3] = numbers[1]; numbers[1] = numbers[3]; /*A correct approach … */ temp = numbers[3]; numbers[3] = numbers[1]; numbers[1] = temp;

29 Printing Array Elements To print an array’s contents, we would use a for loop: for(k = 0; k < 9; k++) { printf( “ %d ”, scores[k]); }//end for

30 Range Checking Unlike some other languages, C does not provide built-in range checking. Thus, it is possible to write code that will produce “out-of- range” errors, with unpredictable results. Common Error (array length is 9): for(j = 1; j <= 9; j++) { scanf( “ %d ”, &scores[j]); }//end for

31 Character Strings

32 Topics Representation Declaration Index of a char in a string String operations Common mistakes

33 Representation Recall: Main memory  contiguous array of cells  each cell has an address 0x1FFF0x20000x20010x20020x1FFE etc

34 ch Representation (cont) Recall: Variable declaration  sets aside a “box” to contain a value Example: char ch; ch = ‘B’; 0x1FFF0x20000x20010x20020x1FFE etc ‘B’

35 Representation (cont) Example: char name[5]; Specifies number of cells in the array String declaration  sets aside an array of cells  each cell contains a char  address of first cell in the array

36 Representation (cont) String declaration  sets aside an array of cells  each cell contains a char  address of first cell in the array Example: char name[5]; 0x2000 0x2004 name is 0x2000

37 Character Arrays vs Character Strings A character string is a char array A character string must have the terminating character (’ \0 ’) The terminating character allows scanf() and printf() to handle character strings

38 Character Strings Declaration 1: char name[5]; Declaration 2: #define MAXLENGTH 5 char name[MAXLENGTH]; 0x2000 0x2004 name is 0x2000

39 String Input/Output #include #define MAXLENGTH 15 int main() { char string1[MAXLENGTH]; char string2[MAXLENGTH]; scanf("%s %s", string1, string2); printf("%s %s\n", string1, string2); return 0; } No ampersand (&)!

40 Character String Declaration Declaration 1: char name[5] = “Ann”; Ann\0 Terminating Character: Marks the end of string Special char: ’\0’ aka NUL (single L) 0x2000 0x2004 name is 0x2000

41 Character String Declaration Declaration 1: char name[5] = “Ann”; Ann\0 0x2000 0x2004 name is 0x2000 Could have defined this as an array: char name[5] = {’A’,’n’,’n’,’\0’};

42 Character String Declaration (cont) Declaration 1: char name[5] = “Ann”; Can store at most 4 letters, because of `\0’ Ann\0 0x2000 0x2004 name is 0x2000

43 Character String Declaration (cont) Declaration 2: char name[] = “Ann”; Takes up an extra cell for ‘\0’ Ann\0 0x2000 0x2003 name is 0x2000

44 Character String Declaration (cont) Declaration 3: char *name = “Ann”; Result is “undefined” if you try to modify this string Ann\0 0x3000 0x3003 0x3000 name

45 Character String Declaration (cont) Declaration 4: char name[]; String with arbitrary length? No! Will cause an error “array size missing in `name’”

46 A Char in a String The size of a character string is fixed Character at position index:  string[index]  first character has index 0

47 char name[8] = “John”; int i = 2; printf(“Char at index %d is %c.\n”, i, name[i]); A Char in a String (cont) output: Char at index 2 is h. index 0index 4 John\0 0x39950x399C name is 0x3995

48 A Char in a String (cont) index 2 John\0 0x39950x399C name is 0x3995 char name[8] = “John”; name[2] = ‘X’; printf(“Name: %s\n”, name); X

49 JoXn\0 0x39950x399C name is 0x3995 output: Name: JoXn index 2 char name[8] = “John”; name[2] = ‘X’; printf(“Name: %s\n”, name); A Char in a String (cont)

50 String Operations #include Operations:  Assignment: strcpy()  Concatenation: strcat()  Comparison: strcmp()  Length: strlen() All rely on and maintain the NUL termination of the strings.

51 #include #define MAXLENGTH 100 int main() { char string1[MAXLENGTH]; char string2[MAXLENGTH]; strcpy(string1, “Hello World!”); strcpy(string2, string1); return 0; } String Operation: Assignment string1: string2: We have previously discussed underlying array copying function

52 String Operation: Assignment (cont) #include #define MAXLENGTH 100 int main() { char string1[MAXLENGTH]; char string2[MAXLENGTH]; strcpy(string1, “Hello World!”); strcpy(string2, string1); return 0; } string1: “Hello World!” string2:

53 String Operation: Assignment #include #define MAXLENGTH 100 int main() { char string1[MAXLENGTH]; char string2[MAXLENGTH]; strcpy(string1, “Hello World!”); strcpy(string2, string1); return 0; } string1: “Hello World!” string2: “Hello World!”

54 char name1[5] = “Ann”; char name2[5] = “Dave”; name2 = name1; Common Mistake 1: Incompatible types Example: Error: “LValue required...”

55 Common Mistake 2: Not enough space Ann\0 0x2000 0x2003 char name[] = “Ann”; strcpy(name, “David”); name is 0x2000

56 Common Mistake 2: Not enough space David\0 0x2003 char name[] = “Ann”; strcpy(name, “David”); 0x2000 name is 0x2000

57 char *name1 = “Ann”; char *name2 = “Dave”; name2 = name1; Caution 1: Pointer Assignment Example:

58 Caution 1: Pointer Assignment Dave\0 0x39900x3994 Ann\0 0x20000x2003 0x2000 name1 0x3990 name2 char *name1 = “Ann”; char *name2 = “Dave”;

59 Caution 1: Pointer Assignment Dave\0 0x39900x3994 Ann\0 0x20000x2003 0x2000 name1 0x2000 name2 name2 = name1;

60 String Operation: Concatenation char string1[MAXLENGTH]; char string2[MAXLENGTH]; strcpy(string1, “Goodbye”); strcpy(string2, “, Cruel ”); strcat(string1, string2); strcat(string1, “World!”); string1: “Goodbye” string2: “, Cruel “

61 char string1[MAXLENGTH]; char string2[MAXLENGTH]; strcpy(string1, “Goodbye”); strcpy(string2, “, Cruel ”); strcat(string1, string2); strcat(string1, “World!”); string1: “Goodbye, Cruel ” string2: “, Cruel ” String Operation: Concatenation (cont)

62 string1: “Goodbye, Cruel, Cruel ” string2: “, Cruel ” String Operation: Concatenation (cont) char string1[MAXLENGTH]; char string2[MAXLENGTH]; strcpy(string1, “Goodbye”); strcpy(string2, “, Cruel ”); strcat(string1, string2); strcat(string1, “World!”);

63 string1: “Goodbye, Cruel, Cruel World!” string2: “, Cruel ” String Operation: Concatenation (cont) char string1[MAXLENGTH]; char string2[MAXLENGTH]; strcpy(string1, “Goodbye”); strcpy(string2, “, Cruel ”); strcat(string1, string2); strcat(string1, “World!”);

64 Common Mistake: char name[5]; strcpy(name, “Ann”); strcat(name, “ Smith”); Not enough space Ann\0 0x2000 0x2004 name is 0x2000

65 Common Mistake: char name[5]; strcpy(name, “Ann”); strcat(name, “ Smith”); Not enough space AnnSmit 0x2000 0x2004 h\0 name is 0x2000

66 strcpy(string1, “Apple”); strcpy(string2, “Wax”); if (strcmp(string1, string2) < 0) { printf(“%s %s\n”, string1, string2); } else { printf(“%s %s\n”, string2, string1); } String Operation: Comparison Returns: negative if string1 < string2 zero if string1 == string2 positive if string1 > string2

67 strcpy(string1, “Apple”); strcpy(string2, “Wax”); if (strcmp(string1, string2) < 0) { printf(“%s %s\n”, string1, string2); } else { printf(“%s %s\n”, string2, string1); } String Operation: Comparison (cont) output: Apple Wax

68 strcpy(string1, “Apple”); strcpy(string2, “Wax”); if (string1 < string2) { printf(“%s %s\n”, string1, string2); } else { printf(“%s %s\n”, string2, string1); } Common Mistake: Wrong Comparison

69 strcpy(string1, “Hi Mum”); strcpy(string2, “Hi Mum”); if ( strcmp(string1, string2) ) { printf(“%s and %s are the same\n”, string1, string2); } Caution 1: Not a Boolean Returns zero if the strings are the same.

70 char string1[100]; strcpy(string1, “Apple”); printf(“%d\n”, strlen(string1)); output: 5 Number of char-s before the `\0’ String Operation: Length

71 Common Mistake: char name[5]; strcpy(name, “David”); Not enough space Don’t forget the ‘\0’ David\0 0x39900x3994 name is 0x3990

72 Summary A string is a contiguous array of chars The string identifier is the address of the first char in the string Individual chars are accessed using the str[index] notation There are C library functions for copying, concatenating and comparing strings


Download ppt "Arrays and Strings Lecture 30. Summary of Previous Lecture In the previous lecture we have covered  Functions Prototypes Variable Scope  Pointers Introduction."

Similar presentations


Ads by Google