1 / 49

CPS 125: Digital Computation and Programming

CPS 125: Digital Computation and Programming. Arrays. Outline. Declaring and Referencing Arrays Array Subscripts Using for Loops for Sequential Access Using Array Elements as Function Arguments Array Arguments Using Character Arrays as Strings Dynamic Allocation of Arrays.

ali-newton
Download Presentation

CPS 125: Digital Computation and 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. CPS 125: Digital Computation and Programming Arrays

  2. Outline • Declaring and Referencing Arrays • Array Subscripts • Using for Loops for Sequential Access • Using Array Elements as Function Arguments • Array Arguments • Using Character Arrays as Strings • Dynamic Allocation of Arrays

  3. Array - Declare • What is an array: aggregate of data items of same type • Why are array needed: keep a number of values (e.g. grades of students in an exam) in memory • Declaring an array int y[6]; /* declares an array of size 6 */ Note: array index (subscript) always starts from 0 0 1 2 3 4 5

  4. Array - Reference • Array elements are individual data items • Each has the same type, size, and name (differentiated by an index or subscript) • Elements are stored in contiguous memory spaces • Referencing array elements • By index (subscript) • Begins with zero, ends with 1 less than number of elements

  5. 12 11 18 20 15 24 Array - Example y[2] y[5] y[0] in this case, y[0] is an int; so are y[2] and y[5] int y[6]; the number of elements allocated; NOT an index!

  6. Array Name • Array name represents address of the 1st element; which is all you need to get to the other elements! • y is the address of array, or the address of first element y[0] • y[0] is a variable • &y[0] is the address of y[0], is equivalent to y

  7. Array Initialization • After declaration y[0]=12; y[1]=11; y[2]=18; y[3]=20; y[4]=15; y[5]=24; • At point of declaration • Can initialize every element allocated int y[6] = {12, 11, 18, 20, 15, 24}; • Can initialize fewer than all elements allocated int y[6] = {12}; /* remaining elements are set to 0 */ • Cannot initialize more elements than allocated int x[2] = {5, 8, 9};

  8. Array Initialization - Example #define MAX 5 int num; int u[MAX + 1]; int v[num]; int w[6] = {1, 2, 3, 4, 5, 6}; int x[ ] = {1, 2, 3, 4, 5, 6}; int y[6] = {1, 2, 3}; int z[] = {1, 2, 3};

  9. Example double x[8] = {16.0, 12.0, 28.0, 26.0, 2.5, 12.0, 14.0, -54.5}; double sum; x[3] = 25.0; sum = x[0] + x[1]; sum += x[2]; x[3] += 1.0; x[2] = x[0] + x[1];

  10. Example #define NUM_STUDENTS 50 int id[NUM_STUDENTS]; double gpa[NUM_STUDENTS]; id and gpa are parallel arrays

  11. Array Subscript • Array subscript (or index) A constant, integer variable, or integer expression y[0] = 3; y[i] = 5; y[2 + 3 * x] = 10; • C does NO bound checking • Result of exceeding bounds is system dependent! • You typically will NOT get a runtime error - it will just allow you to overwrite unprotected areas of memory! • Be careful to only reference existing elements in your arrays!

  12. i = 5; printf(“%.1f”, x[i]); printf(“%.1f”, x[i] + 1); printf(“%.1f”, x[i] + i); printf(“%.1f”, x[i + 1]); printf(“%.1f”, x[i * 2]); printf(“%.1f”, x[(int)x[4]]); printf(“%.1f”, x[i++]); printf(“%.1f”, x[--i]); x[i – 1] = x[i]; x[i] – 1 = x[i];

  13. Using for Loop for Sequential Access • Counting loop, counter variable starts from 0 to < size of array #define SIZE 11 int square[SIZE], i; for (i = 0; i < SIZE; ++i) square[i] = i * i;

  14. Example – Read into Array double abc[25] ; int i ; for (i = 0; i < 25; ++i) { printf (“Enter the %d element \n”, i ) ; scanf ( “%f”, &abc[i] ) ; }

  15. Example – Print from Array double abc[25] ; int i ; for (i = 0; i < 25; ++i) { printf (“The %dth element of array is %lf\n”, i, abc[i]) ; }

  16. Array Elements as Arguments • This is similar to passing simple arguments • The formal parameter should be a simple variable • The actual parameter should be the array name followed by the particular index in [] • Example void do_it(double a1, double *a2p, double *a3p); do_it(x[0], &x[1], &x[2]);

  17. #include <stdio.h> int odd(int num) { return (num % 2 == 1); } int main() { int x[4], i, oddsum = 0, evensum = 0; printf("Enter %d integer values :", 4); for (i = 0; i < 4; i++) { scanf("%d", &x[i]); if ( odd(x[i]) ) oddsum += x[i]; else evensum += x[i]; } printf("The sum of odd elements is : %d\n", oddsum); printf("The sum of even elements is : %d\n", evensum); return 0; }

  18. Array Arguments • The address of array is passed into function • In formal parameter declaration, specifying the array name followed by brackets [] (size is not necessary), e.g. int list[] • int *list is compatible with int list[] • The actual parameter is the array name (no brackets), e.g. list

  19. /* Sets all elements of its array parameter to in_value. */ void fill_array (int list[], /* output - list of n integers */ int n, /* input - number of list elements */ int in_value) /* input - initial value */ { int i; /* array subscript and loop control */ for (i = 0; i < n; ++i) list[i] = in_value; } Call this function: fill_array(y, 10, num); fill_array(x, 5, 1);

  20. Arrays as Input Arguments • In formal parameter declaration const element-type array-name[] • Array variable declared is strictly an input parameter • Its value cannot be modified by function • Still passing array address

  21. int get_max(const int list[], int n) { int i, cur_large; /* largest value so far */ /* First array element is largest so far. */ cur_large = list[0]; /*Compare remaining element to cur_large, save the larger*/ for (i = 1; i < n; ++i) if (list[i] > cur_large) cur_large = list[i]; return (cur_large); }

  22. Return an Array Result void add_arrays(const double ar1[], const double ar2[], double arsum[], int n) { int i; /* Adds corresponding elements of ar1 and ar2 */ for (i = 0; i < n; ++i) arsum[i] = ar1[i] + ar2[i]; } Call this function: add_arrays(x, y, x_plus_y, 5);

  23. Partially Filled Arrays • A program need process many lists of similar data, with different length • Declare an array large enough to hold the largest data set anticipated • This array may be only partially filled • Two sizes: declared size (memory space allocated), actual size (counting elements in use)

  24. Searching (Linear Search) • Searching means scanning though a list of items or records to find a particular item • User specifies the target item • If the target item is found, the record or its location is returned, otherwise, an appropriate message or flag is returned • Linear search means searching through the list sequentially until the target item is found or the list is exhausted

  25. 1. Assume the target has not been found 2. Start with the initial array element 3. Repeat while the target is not found and there are more array elements 4. If current element matches the target 5. Set flag to indicate target has been found else 6. Advance to next array element 7. If the target is found 8. Return the target index as search result else 9. Return -1 as the search result

  26. Sorting (Bubble Sort) • Compare adjacent pairs of an array • If the first is larger than second, interchange the two elements • Repeat the above two steps until the array is sorted in increasing order • After one pass, the element with the largest key has been “bubbled” to the end of the list • The procedure continues by successively increasing the starting point in the list by 1

  27. 44 33 55 22 33 44 22 55 33 22 44 55 22 33 44 55 Original array Pass 1 Pass 2 Pass 3 Total number of pass required in bubble sort algorithm =n-1 Total number of comparisons required in first pass =n-1 Total number of comparisons required in second pass =n-2 Total number of comparisons required in third pass =n-3 Where n is size of the list (or Array).

  28. Strings • Strings are arrays of char char str[50]; • May vary in length – not all positions are used • Terminated by ‘\0’ • Null terminating character • Array size must accommodate ‘\0’ • Individual elements are char

  29. String - Example elements past the null are not part of the string char name[6] = "Sam"; S a m \0 name name[0] name[5] indicates end of string, not end of array!

  30. String Initialization • Initialize • Can do each char separately or as a string constant • Initialization list of individual chars. Note null character at end – required for a string! char name[6] = {‘C’, ‘h’, ‘u’, ‘c’, ‘k’, ‘\0’}; • Double quotes implies a null character at the end char name[6] = “Sam”; • Array of Strings char month[12][10] = {“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”};

  31. Input/Output with printf & scanf • Placeholder %s • printf(“Topic: %s\n”, string_var); • If string_var contains no null character, printf will continue to display content of memory as characters until it encountered a null character or caused a run-time error • Right justification: printf(“%20s\n”, president); • Left justification: printf(“%-20s\n”, president);

  32. Example with scanf scanf(“%s%d%s%d”, dept, &course_num, days, &time); > MATH 1270 TR 1800 > MATH 1270 TR 1800 > MATH1270 TR 1800 > MATH,1270,TR,1800 char dept[10]; Space not allocated for dept M A T H , 1 2 7 0 , T R , 1 8 0 0 \0

  33. #define NUM_NAMES 30 #define NAME_LEN 25 char names[NUM_NAMES][NAME_LEN]; int age[NUM_NAMES]; for (i=0; i<NUM_NAMES; ++i) { scanf(“%s%d”, names[i], &ages[i]; printf(“%-35s %d\n”, names[i], ages[i]); }

  34. String Functions • #include <string.h> • strcpy, strncpy • strcat, strncat • strlen • strcmp • strstr

  35. strcpy, strncpy • strcpy(destination, source) strcpy(one_str, “Test string 1”); • Overwrites characters in destination with characters from source • Stops at ‘\0’ in source • strncpy(destination, source, n) • Same as strcpy, excepts copies up to n characters • No ‘\0’ appended at the end, have to assign by yourself destination[n] = ‘\0’;

  36. strcat, strncat • strcat(destination, source) strcat(one_str, “ and 2”); • Appends characters in source to characters in destination • Stops at ‘\0’ in source • strncat(destination, source, n) • Same as strcat, excepts copies up to n characters • No ‘\0’ appended at the end, have to assign by yourself strcat(destination, “\0”);

  37. strlen • strlen(string) len = strlen(one_string); • Returns the number of characters in string • Does not include ‘\0’

  38. strcmp • strcmp(string1, string2) • Compares one string to another • Returns • < 0 if string1 < string2 • 0 if string1 == string2 • > 0 if string1 > string2 • strcmp(“thrill”, “throw”) strcmp(“throw”, “thrill”) • strcmp(“end”, “end”) • strcmp(“joy”, “joyous”)

  39. printf("Enter list of words on as many lines as you like.\n"); printf("Separate words by at least one blank.\n"); printf("When done, enter %s to quit.\n", SENT); for (scanf("%s", word); strcmp(word, SENT) != 0; scanf("%s", word)) { /* process word */ }

  40. strstr • strstr(string1, string2); • Returns the position where string2 begins in string1 • Returns NULL if string1 does not contain string2 • char * pos; pos = strstr(“abcdef”, “xyz”); pos = strstr(“abcdef”, “cd”);

  41. Case Study • Problem: A genetic engineer is developing a program to identify palindromes of a certain length in strings representing the nucleotide sequences of a portion of a DNA molecule. A-T-C-G-C-A-T-G-C-G-T-A-G T-A-G-C-G-T-A-C-G-C-A-T-C

  42. Case Study • Analysis Constant : STRANDSIZ 100 Inputs: char strand1[STRANDSIZ], char strand2[STRANDSIZ]; int palin_len; Outputs: index and value of each palindromic sequence of length palin_len

  43. Case Study • Design Algorithm: 1. Get input data: complementary strands and palindrome length 2. For each starting subscript of a substring of the desired length 2.1 if substring from strand1 matches the reverse of corresponding substring of strand2 2.1.1 Print the position and two substrings

  44. Dynamic Allocation of Arrays • Stack: statically allocated memory space • Sizes of variables in the function data areas are known when program is compiled • Space can be automatically made available for reuse after function call returns • Heap: dynamically allocated memory space • Spaces are allocated while program is running • In response to specific requests • Spaces should be explicitly given back for reuse

  45. Dynamic Memory Allocation • #include <stdlib.h> • double *nums_list; nums_list = (double *) calloc(list_size, sizeof(double)); …… free(nums_list);

  46. Stack and Heap Function Data Area Heap string1 array_of_nums

  47. double *list; int i, howmany; printf(“How many numbers? => “); scanf(“%d”, &howmany); printf(“Enter %d numbers. => “, howmany); for (i=0; i<howmany; ++i) scanf(“%lf”, &list[i]); printf(“your list is: “); for (i=0; i<howmany; ++i) printf(“%10.2f”, list[i]); printf(“\n”);

  48. Common Programming Errors • Subscript-range error: out of range • Normally no run-time error, just incorrect results • Responsibility of programmer • Caused by incorrect subscript expression, a loop counter error, or a non-terminating loop • No & for passing array as argument even if for output • Use & for passing array elements as output • Overflow of character arrays allocated for strings • All strings end with the null character • Ensure enough stack space for large array • Allocate memory to array before using it

More Related