Complex Data Types Arrays Structs Topic 7 Plan

  • Slides: 49
Download presentation
Complex Data Types: Arrays & Structs Topic 7 Plan for the Day: Array Basics

Complex Data Types: Arrays & Structs Topic 7 Plan for the Day: Array Basics Strings (aka character arrays) Structures

Arrays

Arrays

Array Overview • • • ordered collection of items stored in contiguous memory all

Array Overview • • • ordered collection of items stored in contiguous memory all items, called elements, are of same type array cannot be resized indexing starts at 0 – offset from beginning of array name of array is pointer (memory address) of 1 st array element Declaration syntax: <elt-type> <array-name>[size]; • sets aside size*sizeof(elt-type) bytes Example: int grades[80]; Example: int nums[5] = {1, 2, 3, 4, 5};

Can we solve this problem? • Consider the following program (input underlined): How many

Can we solve this problem? • Consider the following program (input underlined): How many days' temperatures? 7 Day 1's high temp: 45 Day 2's high temp: 44 Day 3's high temp: 39 Day 4's high temp: 48 Day 5's high temp: 37 Day 6's high temp: 46 Day 7's high temp: 53 Average temp = 44. 6 4 days were above average.

Why the problem is hard • We need each input value twice: – to

Why the problem is hard • We need each input value twice: – to compute the average (a cumulative sum) – to count how many were above average • We could read each value into a variable. . . but we: – don't know how many days are needed until the program runs – don't know how many variables to declare • We need a way to declare many variables in one step.

Why the problem is hard • We need each input value twice: – to

Why the problem is hard • We need each input value twice: – to compute the average (a cumulative sum) – to count how many were above average • We could read each value into a variable. . . but we: – don't know how many days are needed until the program runs – don't know how many variables to declare • We need a way to declare many variables in one step. • Solution: an array

Arrays Example: int arr[10] = {12, 49, -2, 26, 5, 17, -6, 84, 72,

Arrays Example: int arr[10] = {12, 49, -2, 26, 5, 17, -6, 84, 72, 3}; index 0 1 value 12 49 element 0 2 3 4 5 6 -2 26 5 17 -6 element 4 7 8 84 72 9 3 element 9

Array declaration <type> <name>[size]; <type> <name>[ ] = {initial-values}; – Example: int numbers[10] =

Array declaration <type> <name>[size]; <type> <name>[ ] = {initial-values}; – Example: int numbers[10] = {0}; index 0 1 2 3 4 5 6 7 8 9 value 0 0 0 0 0

Initializing an Array • An array initializer is a list of values enclosed in

Initializing an Array • An array initializer is a list of values enclosed in braces: int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; • If initializer too short, remaining elements are set to 0: int a[10] = {0}; • If an initializer is present, the length of the array may be omitted, and is determined by the compiler: int a[ ] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; • Can declare these to be unchangeable if needed const int a[ ] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

Accessing elements <name>[<index>] // access <name>[<index>] = <value>; // modify – Example: int numbers[10]

Accessing elements <name>[<index>] // access <name>[<index>] = <value>; // modify – Example: int numbers[10] = {0}; numbers[0] = 27; numbers[3] = -6; printf("%dn", numbers[0]); if (numbers[3] < 0) { printf("Element 3 is negative. "); } index 0 1 2 3 4 5 6 7 value 27 0 0 0 -6 0 0 0 8 9 0 0

Arrays and Loops Example: int a[10], i; for (i = 0; i < 10

Arrays and Loops Example: int a[10], i; for (i = 0; i < 10 ; i++) {a[i] = 10 - i; } Warning: Array bounds in C are not checked; when a subscript goes out of bounds, the result is unpredictable. int a[10]; for (int i = 1; i <= 10; i++) a[i] = 2*i; What's the sizeof (a) ? What's the sizeof (a) / sizeof(a[0]) ? // wrong!

Weather question • Use an array to solve the weather problem: How many days'

Weather question • Use an array to solve the weather problem: How many days' temperatures? 7 Day 1's high temp: 45 Day 2's high temp: 44 Day 3's high temp: 39 Day 4's high temp: 48 Day 5's high temp: 37 Day 6's high temp: 46 Day 7's high temp: 53 Average temp = 44. 6 4 days were above average.

Weather Answer #include<stdio. h> // Reads temperatures from the user, computes average and #

Weather Answer #include<stdio. h> // Reads temperatures from the user, computes average and # days above average int main() { int days; printf("How many days' temperatures? "); scanf(" %d", &days); int temps[days]; // array to store days' temps int sum = 0; // Read and store each day's temperature for(int i = 0; i < days; i++) { printf("Day %d's high temp: ", i+1); scanf(" %d", &temps[i]); sum += temps[i]; } double average = (double) sum/days; // see if each day is above average int count = 0; for(int i = 0; i < days; i++) { if(temps[i] > average) count++; } // report results printf("Average temp = %. 1 fn", average); printf("%d days above averagen", count); }

"Array mystery" problem • traversal: An examination of each element of an array. •

"Array mystery" problem • traversal: An examination of each element of an array. • What element values are stored in the following array? int a[] = {1, 7, 5, 6, 4, 11}; for (int i = 0; i < sizeof(a)/sizeof(a[0])-1; i++) { if (a[i] > a[i + 1]) { a[i + 1] = a[i + 1] * 2; } } index 0 1 2 3 4 value 1 7 5 6 4 5 6 14 11

"Array mystery" problem • traversal: An examination of each element of an array. •

"Array mystery" problem • traversal: An examination of each element of an array. • What element values are stored in the following array? int a[] = {1, 7, 5, 6, 4, 11}; for (int i = 0; i < sizeof(a)/sizeof(a[0])-1; i++) { if (a[i] > a[i + 1]) { a[i + 1] = a[i + 1] * 2; } } index 0 1 value 1 7 2 3 10 12 4 8 5 6 14 22

Array Arguments • Often must pass length of array as well as array •

Array Arguments • Often must pass length of array as well as array • Array argument: what's actually passed is pointer to (memory address) array int foo(int arr[]) { // sizeof won't tell us # of elts in arr parameter } • Exercise: Write a function that takes an int array and the length of the array, and returns the sum of its elements. int sum. Array(int a[], int len) {. . .

Array Limitations • You cannot resize an array • You cannot compare arrays with

Array Limitations • You cannot resize an array • You cannot compare arrays with == or != – char s[10], t[10]; – if(s == t) {. . . } // s and t are memory addresses • You cannot put array name on left side of assignment – char s[10]; s = "abc"; // NO • You cannot use sizeof to determine length of array parameter

Strings

Strings

Character Arrays • Strings are represented as arrays of characters • The end of

Character Arrays • Strings are represented as arrays of characters • The end of the string is specified with '' (aka null character) • "hello" is represented with array {'h', 'e', 'l', 'o', ''} Examples: char my. String[] = "hello"; char my. String[10] = "hello"; char my. String[] = {'h', 'e', 'l', 'o', ''};

String Variables • A "string" in C is a one-dim array of chars •

String Variables • A "string" in C is a one-dim array of chars • Array length accounts for null character at end #define STR_LEN 80 char str[STR_LEN+1]; • If string initializer does not fill array, remaining elements filled with null char ('') char date[9] = "June 14"; date 0 'J' 1 2 'u' 'n' 3 'e' 4 5 6 7 8 '1' '4' ''

Reading strings char name[10]; printf("Enter your name: "); scanf("%9 s", name); • Don't exceed

Reading strings char name[10]; printf("Enter your name: "); scanf("%9 s", name); • Don't exceed array's bounds • Leave room for null character at end of string • name is the address of the array Output: Enter your name: Mary. Eberlein name: Mary. Eberl

Accessing the Characters • Function that counts and returns the number of spaces in

Accessing the Characters • Function that counts and returns the number of spaces in a given argument string: Can't change s int count. Spaces(const char s[]) { int count, i; count = 0; for(i = 0; s[i] != ''; i++) { if(s[i] == ' ') count++; } return count; }

Comparing Strings • • Functions in header file string. h are used for string

Comparing Strings • • Functions in header file string. h are used for string operations Cannot compare two strings with == int strcmp(char s[], char t[]) compares two strings in dictionary (lexicographic) order – capital letters less than lowercase letters – Returns negative if s comes before t – Returns 0 if s is the same string as t – Returns positive if s comes after t Examples: strcmp("Abe", "abe") strcmp("123", "123") // value is negative // value is 0

String Manipulation: Copy & Concatenation • strcpy(str 1, str 2): copies str 2 into

String Manipulation: Copy & Concatenation • strcpy(str 1, str 2): copies str 2 into str 1 – does not check that str 1 is long enough to hold str 2! char str 1[10], str 2[10]; strcpy(str 2, "abcd"); // str 2 contains "abcd" strcpy(str 1, str 2); //str 1 contains "abcd" • strncpy(str 1, str 2, n): copies up to n characters • strcat(str 1, str 2): appends contents of str 2 to end of str 1 – doesn't check that str 1 is long enough • strncat(str 1, str 2, n): appends up to n characters

String Copy char s[10] = "help"; char *foo = "War of the worlds"; strncpy(s,

String Copy char s[10] = "help"; char *foo = "War of the worlds"; strncpy(s, foo, 9); // copy 9 chars into positions 0 -8 printf("s is %sn, s); printf("length of s: %lun", strlen(s)); printf("Last char in s: %dn", s[9]); Output: s is War of th length of s: 9 Last char in s: 0

strlen Function • strlen(str): returns length of string stored in array str (not including

strlen Function • strlen(str): returns length of string stored in array str (not including null character at end) int len; char str[10] = "abc"; len = strlen(str); // len is 3

Search for chars and substrings char *strchr(s, ch): returns pointer to first occurrence of

Search for chars and substrings char *strchr(s, ch): returns pointer to first occurrence of ch in s, or NULL if ch is not found in s char *strstr(s 1, s 2): returns a pointer to first occurrence of s 2 in s 1

String Example #include<stdio. h> #include<string. h> int main() { printf("Does Alf come before alf?

String Example #include<stdio. h> #include<string. h> int main() { printf("Does Alf come before alf? %sn", strcmp("Alf", "alf") < 0 ? "yes" : "no"); printf("Does bass come before alf? %sn", strcmp("bass", "alf")< 0 ? "yes" : "no"); char str 1[10] = "hello"; char str 2[10] = "world"; strncat(str 1, str 2, 4); printf("hello concatenated with world: %sn", str 1); int len = strlen(str 1); printf(""%s" has length %dn", str 1, len); char str 3[] = "hello"; // Does hello contain hell? if(strstr(str 3, "hell") != NULL){ printf("hello contains helln"); } else printf("hello does not contain helln"); } Better to omit: != NULL Output: Does Alf come before alf? yes Does bass come before alf? no hello concatenated with world: helloworl "helloworl" has length 9 hello contains hell

Useful Functions (stdlib. h) Function double atof(const char str[]) int atoi(const char str[]) double

Useful Functions (stdlib. h) Function double atof(const char str[]) int atoi(const char str[]) double strtod(const char str[], char **endptr) Description Converts string str to a double Converts string str to an int Converts str to double (and returns the double), endptr points to the next character in str after the numerical value int abs(int x) returns the absolute value of integer x

Example char str[] = "3. 14 This is pi"; char *rest. Of. String; double

Example char str[] = "3. 14 This is pi"; char *rest. Of. String; double num; num = strtod(str, &rest. Of. String); printf("The number is %lfn", num); printf("The remaining string: %sn", rest. Of. String); Output: The number is 3. 140000 The remaining string: This is pi

Example #include<stdio. h> #include<ctype. h> #include<stdlib. h>. . . // Q for queen, 10,

Example #include<stdio. h> #include<ctype. h> #include<stdlib. h>. . . // Q for queen, 10, 9, etc. char card. Value[3]; puts("Enter your card's value: "); scanf("%2 s", card. Value); if(isdigit(card. Value[0])) { int value = atoi(card. Value); printf("Value: %dn", value); } Other useful character handling functions in ctype. h: see 23. 5, p. 612 isalnum(c) : is c alphanumeric? isalpha(c): is c alphabetic? isdigit(c): is c a decimal digit? islower(c): is c a lower-case letter? toupper(c): returns uppercase version of c if it's a letter, c otherwise

Exercise Write a version of the atoi function. Your function only needs to work

Exercise Write a version of the atoi function. Your function only needs to work on strings that contain positive integers. int my. Atoi(char str[]) { // put your code here return result; }

Exercise int my. Atoi(char str[]) { int result = 0; for(int i = 0;

Exercise int my. Atoi(char str[]) { int result = 0; for(int i = 0; str[i] != ''; i++) { result = result*10 + str[i] - '0'; } return result; } int main() { char str[] = "892"; int value = my. Atoi(str); printf("%dn", value); } Output: 892

command line arguments

command line arguments

Input on command line int main(int argc, char* argv[]) {…} • argc: # of

Input on command line int main(int argc, char* argv[]) {…} • argc: # of arguments on command line – includes name of executable • argv[]: array of strings on command line

Example int main(int argc, char *argv[]) { for(int i = 0; i < argc;

Example int main(int argc, char *argv[]) { for(int i = 0; i < argc; i++) { printf("arg %d = %sn", i, argv[i]); } } Sample Run: bash-3. 2$ gcc comm. Line. c bash-3. 2$. /a. out one two three arg 0 =. /a. out arg 1 = one arg 2 = two arg 3 = three

Command Line Args int main(int argc, char *argv[]) { if(argc < 2) printf("Need an

Command Line Args int main(int argc, char *argv[]) { if(argc < 2) printf("Need an integer!"); else { int n = atoi(argv[1]); int nums[n]; // legal in C 99 for(int i = 0; i < n; i++) } nums[i] = i; } for(int i = 0; i < n; i += 2) printf("%dn", nums[i]); } Output? % gcc –o prog. c %. /prog 4 Note: argv[0] is. /prog argv[1] is 4

Exercise • Write a program that takes integers on the command line and prints

Exercise • Write a program that takes integers on the command line and prints their sum. You may assume that all the command line arguments other than the executable name are integers. • Example run: . /a. out 3 5 1 Sum = 9

structs

structs

Structures • struct: Collection of variables with one name – the variables are called

Structures • struct: Collection of variables with one name – the variables are called members or fields – may be different types • Use structs to – keep related data together – pass fewer arguments – return multiple values as a struct

structure tag Example A struct for data related to our class: struct ee. Class

structure tag Example A struct for data related to our class: struct ee. Class { int class. Num; char meeting. Room[20]; char course. Name[30]; }; • Variable declaration: struct ee. Class ee 312; • Member (or field) access: ee 312. class. Num = 312; Or use a typedef: typedef struct ee. Class{ int class. Num; char meeting. Room[20]; char course. Name[30]; } EEClass; EEClass ee 312; ee 312. class. Num = 312; strcpy(ee 312. meeting. Room, "EER 3");

structs • Record containing related data values that are used together • Fields stored

structs • Record containing related data values that are used together • Fields stored in contiguous memory • Like an array, except: – data values in struct have names – access fields with "dot" operator, not [] Suppose you are writing a class scheduling system. You'd probably need to pass the same set of data to many functions. void catalog(char course. Name[], int course. Number, int sec. ID) {…} Instead: combine that data in a struct

Structures struct UTCourse { char course. Name[50]; int course. Number; int sec. ID; };

Structures struct UTCourse { char course. Name[50]; int course. Number; int sec. ID; }; struct UTCourse EE 312_00 = {"Software Design & Implementation I", 312, 16100}; • Now your function might look like this: void catalog(struct UTCourse my. Class) {…}

Field Access • Use the dot operator to access fields (and the variable name)

Field Access • Use the dot operator to access fields (and the variable name) typedef struct name { char first[20]; char last[20]; } full. Name; full. Name me = {"Mary", "Eberlein"}; printf("Hey %sn", me. last);

Designated Initializers (C 99) typedef struct name { char first[20]; char last[20]; } full.

Designated Initializers (C 99) typedef struct name { char first[20]; char last[20]; } full. Name; • Value can be labeled with the field name: full. Name person = {. last = "Presley", . first = "Elvis"}; • If field omitted from initializer, set to 0

Operations on structs • The. access operator has precedence over nearly all other operators

Operations on structs • The. access operator has precedence over nearly all other operators • Example: typedef struct { int part. Num; char part. Name[30]; int on. Hand; } part; part 1 = {. part. Num = 311, . part. Name = "usb"}; scanf("%d", &part 1. on. Hand); //. operator higher precedence than & • Assigning one struct to another makes a copy: part 2 = part 1; // copy each field of part 1 into part 2 • Note: structs cannot be compared with == or !=

Passing structs void print. Name(struct name p) { printf("First name: %sn", p. first); printf("Last

Passing structs void print. Name(struct name p) { printf("First name: %sn", p. first); printf("Last name: %sn", p. last); } Function call: print. Name(person); Output: First name: Elvis Last name: Presley

struct return values struct name make. AName(char *first. Name, char* last. Name) { struct

struct return values struct name make. AName(char *first. Name, char* last. Name) { struct name elvis; strcpy(elvis. first, first. Name); strcpy(elvis. last, last. Name); return elvis; } Function call: struct name the. King = make. AName("Elvis", "Presley");

Example #include<stdio. h> #include<string. h> typedef struct { char first[20]; char last[20]; } full.

Example #include<stdio. h> #include<string. h> typedef struct { char first[20]; char last[20]; } full. Name; Output: First name: Bruce Last name: Lee Firstname: Bruce Last name: Lee void print. Name(full. Name p); full. Name make. AName(char *first. Name, char *last. Name); int main() { full. Name one. Person = make. AName("Bruce", "Lee"); print. Name(one. Person); full. Name someone = one. Person; print. Name(someone); }