1 / 16

16.216 ECE Application Programming

16.216 ECE Application Programming. Instructor: Dr. Michael Geiger Fall 2013 Lecture 20 Arrays and functions (continued). Lecture outline. Announcements/reminders Program 6 due 10/28 Review Two-dimensional arrays Arrays and functions Today’s lecture

meir
Télécharger la présentation

16.216 ECE Application Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 16.216ECE Application Programming Instructor: Dr. Michael Geiger Fall 2013 Lecture 20 Arrays and functions (continued)

  2. Lecture outline • Announcements/reminders • Program 6 due 10/28 • Review • Two-dimensional arrays • Arrays and functions • Today’s lecture • Two-dimensional arrays and functions • Character arrays and strings ECE Application Programming: Lecture 20

  3. Review: arrays & pointers • Arrays: groups of data with same type • x[10] has 10 elements, x[0] through x[9] • Can also define with initial values • e.g. double list[] = {1.2, 0.75, -3.233}; • Must be sure to access inside bounds • Array name is a pointer • Arrays are always passed by address to functions • Can use pointer to access array • Can use arithmetic to move pointer through array ECE Application Programming: Lecture 20

  4. Review: 2D arrays • Declared similarly to 1D arrays • Example (see below): int x[3][4]; • Index elements similarly to 1-D arrays • Initialize:int y[3][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} }; • Typically used with nested for loops • Can pass to functions—must specify # columns ECE Application Programming: Lecture 20

  5. 2-D arrays and functions • When passing 2-D array to function, can omit first dimension (rows) but must list columns • Example: // Assume n = # of rows int f(intarr[][4], int n); int main() { int x[3][4]; f(x, 3); ... } ECE Application Programming: Lecture 20

  6. Example: 2-D arrays and functions • Say we have a program that stores student exam scores in a 2-D array: • Each row represents an individual student • Each column represents one of the 3 exams • Write functions to: • Calculate the exam average for each student and store it in a 1-D array that is accessible in the main program • Assume all exams have equal weight • Calculate the average for each exam and store it in a 1-D array that is accessible in the main program • Each function takes the same arguments: • The 2-D array • The # of students in the class • The 1-D array that will be used to hold the averages ECE Application Programming: Lecture 20

  7. Example solution void studentAvg(double grades[][3], intnStudents, double averages[]) { inti, j; // Row/column # /* Go through each row, sum all columns, and divide by 3 to get each student’s avg */ for (i = 0; i < nStudents; i++) { averages[i] = grades[i][0]; // Initialize sum for (j = 1; j < 3; j++) { averages[i] += grades[i][j]; } averages[i] /= 3; } } ECE Application Programming: Lecture 20

  8. Example solution (cont.) void examAvg(double grades[][3], intnStudents, double averages[]) { inti, j; // Row/column # /* Go through each column, sum all rows, and divide by nStudents to get each exam avg */ for (j = 0; j < 3; j++) { averages[j] = grades[0][j]; // Initialize sum for (i = 1; i < nStudents; i++) { averages[j] += grades[i][j]; } averages[j] /= nStudents; } } ECE Application Programming: Lecture 20

  9. Strings in C • Strings in C: null-terminated arrays of characters • “Hello”{‘H’, ‘e’, ‘l’, ‘l’, ‘o’, 0} • Null character = 0 = ‘\0’ • Can declare array to hold string • Need space to hold null: char hello[5] would be too small • Can use string constants to directly initialize char hello[] = “Hello”; • Equivalent to: char hello[6]; hello[0] = ‘H’; hello[1] = ‘e’; hello[2] = ‘l’; hello[3] = ‘l’; hello[4] = ‘o’; hello[5] = 0 --OR-- hello[5] = ‘\0’; ECE Application Programming: Lecture 7

  10. Strings, output, and functions • Can pass string as array or pointer: char * • printf(), scanf() take char * as first argument • Given string char hello[] from previous slide: • Print directly: printf(hello); • Print w/formatting using %s: printf(“%s\n”, hello); • Print individual character: printf(“%c\n”, hello[1]); ECE Application Programming: Lecture 7

  11. String functions • Things we’d like to do with strings: • Set one equal to another • Compare two strings • Find # characters in string • String may not fill array (“buffer”) allocated for it • “Add” two strings together • “abc” + “def” = “abcdef” ECE Application Programming: Lecture 7

  12. String functions (cont.) • In <string.h> library: • Copying strings: • char *strcpy(char *dest, const char *source); • char *strncpy(char *dest, const char *source, size_t num); • Return dest • Does not append ‘\0’ unless length of source < num • Comparing strings: • intstrcmp(const char *s1, const char *s2); • intstrncmp(const char *s1, const char *s2, size_t num); • Character-by-character comparison of character values • Returns 0 if s1 == s2, 1 if s1 > s2, -1 if s1 < s2 ECE Application Programming: Lecture 7

  13. String functions (cont.) • Find # of characters in a string • size_tstrlen(const char *s1); • Returns # characters before ‘\0’ • Not necessarily size of array • “Add” strings together—string concatenation • char *strcat(char *dest, const char *source); • char *strncat(char *dest, const char *source, size_t num); • Returns dest ECE Application Programming: Lecture 7

  14. Example: Strings • What does the following program print? int main() { char s1[15]; int n1; char s2[10] = “.216”; int n; strncpy(s1, “16”, 15); n1 = strlen(s1); printf(“s1 = %s\n”, s1); printf(“Length of s1 = %d\n\n”, n1); printf(“%c\n\n”, s1[1]); strncat(s1,s2,10); n1 = strlen(s1); printf(“s1 = %s\n”, s1); printf(“Length of s1 = %d\n\n”, n1); // Assume user inputs: ABC ABD printf(“Enter two strings:”); scanf(“%s%s”, s1, s2); n = strncmp(s1, s2, 15); if (n > 0) printf(“%s > %s\n”, s1, s2); else if (n < 0) printf(“%s < %s\n”, s1, s2); else printf(“%s == %s\n”, s1, s2); return 0; } ECE Application Programming: Lecture 7

  15. Example solution s1 = 16 Initial value of s1 Length of s1 = 2 6 s1[1] s1 = 16.216 s1 after strncat() Length of s1 = 6 Enter two strings: ABC ABD ABC < ABD Result of strncmp() ECE Application Programming: Lecture 7

  16. Final notes • Next time • Finish discussion of character arrays and strings • Reminders: • Program 6 due 10/28 ECE Application Programming: Lecture 20

More Related