1 / 35

Arrays

Arrays. Simple data types use a single memory cell to store a variable: int x; A data structure is a composite of related data items stored under a same name. Array is one of such data structures.

metta
Télécharger la présentation

Arrays

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. Arrays Simple data types use a single memory cell to store a variable: int x; A data structure is a composite of related data items stored under a same name. Array is one of such data structures. For example it is easier to write a program that processes exam scores for a class by using an array because all scores can be stored in one area of the memory and can be accessed together. A. Abhari CPS125

  2. Declaring and Referencing Arrays • Both name of the array and its number of cells should be defined: For example double x[8] instructs the compiler to associate eight adjacent memory cells of double type with the name of x. • Array subscript is a value or expression enclosed in the brackets after array name, that shows an array element. For example x[3] means element 3 of array x. A. Abhari CPS125

  3. Declaring and Referencing Arrays • The range of array subscript is from zero to one less than the number of memory cells in the array. • array subscript always starts from 0 x[0] x[1] x[2] x[3] x[4] x[5] x[6] x[7] 16.0 12.0 28.0 26.0 2.5 12.0 14.0 -54.0 same type A. Abhari CPS125

  4. Parallel Arrays • Two or more arrays with the same number of elements for storing related information: int id[NUM_STUDENTS] double gpa[NUM_STUDENTS] 5503 2.71 id[0] gpa[0] 4556 3.09 id[1] gpa[1] A. Abhari CPS125

  5. More on Array Declaration • One or more arrays can be declared in one single type declaration: int factor[12], n, pins[6]; • Array can be initialized in the time of declaration int prime_1t_5[ ] = { 2,3,5}; It is same as initializing a variable when we declare it: int sum=0; A. Abhari CPS125

  6. Array Subscript • Array subscript (or index) Can be a constant, integer variable, or integer expression x[0] = 2; x[i] = 5; x[2 + 3 * x] = 7; • C does NO bound checking • Result of exceeding bounds is system dependent! • Sometimes a runtime error is printed - but sometimes subscript error may cause the side effect • Only the existing elements in the array should be referenced A. Abhari CPS125

  7. 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]; A. Abhari CPS125

  8. Using for Loops for Sequential Access • 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; A. Abhari CPS125

  9. Storing Input Values into the Array elements • The variable i is using as control loop variable and array subscript #define MAX_ITEM 11 int x[MAX_ITEM], i; for (i = 0; i < MAX_ITEM; ++i) scanf("%lf", &x[i]); output parameter A. Abhari CPS125

  10. Printing the Values of Array Elements #define MAX_ITEM 11 double x[MAX_ITEM]; int i; for (i = 0; i < MAX_ITEM; ++i) { printf (“The %dth element of array is %lf\n”, i, x[i] ) ; } input parameter A. Abhari CPS125

  11. /* * Computes the mean and standard deviation of an array of data and * displays the difference between each value and the mean. */ #include <stdio.h> #include <math.h> #define MAX_ITEM 8 /* maximum number of items in list of data */ int main(void) { double x[MAX_ITEM], /* data list */ mean, /* mean (average) of the data */ st_dev, /* standard deviation of the data */ sum, /* sum of the data */ sum_sqr; /* sum of the squares of the data */ int i; /* Gets the data */ printf("Enter %d numbers separated by blanks\n> ", MAX_ITEM); for (i = 0; i < MAX_ITEM; ++i) scanf("%lf", &x[i]); A. Abhari CPS125

  12. /* Computes the sum and the sum of the squares of all data */ sum = 0; sum_sqr = 0; for (i = 0; i < MAX_ITEM; ++i) { sum += x[i]; sum_sqr += x[i] * x[i]; } /* Computes and prints the mean and standard deviation */ mean = sum / MAX_ITEM; st_dev = sqrt(sum_sqr / MAX_ITEM - mean * mean); printf("The mean is %.2f.\n", mean); printf("The standard deviation is %.2f.\n", st_dev); /* Displays the difference between each item and the mean */ printf("\nTable of differences between data values and mean\n"); printf("Index Item Difference\n"); for (i = 0; i < MAX_ITEM; ++i) printf("%3d%4c%9.2f%5c%9.2f\n", i, ' ', x[i], ' ', x[i] - mean); return (0); } A. Abhari CPS125

  13. Enter 8 numbers separated by blanks > 16 12 6 8 2.5 12 14 -54.5 The mean is 2.00. The standard deviation is 21.75. Table of differences between data values and mean Index Item Difference 0 16.00 14.00 ……………………… A. Abhari CPS125

  14. Using Array Elements as Function Arguments The formal parameter is a simple variable • The actual parameter is the array name followed by the particular index in [] • Example function prototype  void do_it(double a1, double *a2p, double *a3p); In the function body *a2p=…. *a3p=…. function call do_it(x[0], &x[1], &x[2]); A. Abhari CPS125

  15. Array Arguments • The argument declaration of the array does not indicate the size of the array because compiler does not need to know that. • Array name with no subscript is a pointer to the initial array element /* Sets all elements of its array parameter to in_value. */ void fill_array (intlist[], /* 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; } function call: fill_array(y, 10, num); fill_array(x, 5, 1); A. Abhari CPS125

  16. Array Arguments • int *list also also can be used instead of int list[] in a formal parameter list Calling function data area function fill_array data area list [0] [1] [2] [3] [4] A. Abhari CPS125

  17. Arrays as Input Arguments /* Returns the largest of the first n values in the array */ int get_max(const int list[], int n) { const indicates that array is input and can not be modified 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); } A. Abhari CPS125

  18. Returning an Array Result • In C it is not legal for a function return type to be an array, therefore, array should be used as output parameter. For example: 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); A. Abhari CPS125

  19. Partially Filled Array function void fill( int max, double sentinel, double x[], int *size) ………….. status = scanf( “%f” , &data); while (status == 1 && data != sentinel && i < max) { x[i] = data; ++i; status = scanf( “%f” , &data); } …………. *size = i; ………….. main program double y [1000]; int used; ……….. fill(1000,-1, y, &used); …………

  20. Searching in the Array • Linear search int search (const in arr[], int target, int n) { int i, found=0, where; i=0; while ( !found && i<n) { if (arr[i] == target) found = i; else ++i; } if (found) where = i; else where= -1; return (where) } A. Abhari CPS125

  21. Strings • printf (“Average = %.2f”, avg); • #define ERROR “****error******” • Strings are arrays of char, For example: char str[40] = “value” ; Terminated by ‘\0’ at str[5] • Null character marks the end of string • Array size must be more than string length plus ‘\0’ • All C string handling functions ignore whatever is stored in the cells following the null character A. Abhari CPS125

  22. String • Individual elements are char • char course[6] = “math"; m a t h \0 char letter[1] =“A” A \n A. Abhari CPS125

  23. Strings • Array of Strings char month[12][10] = {“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”}; • Input/output printf(“Topic: %s\n”, string_var); Right justification: printf(“%10s\n”, president); president Left justification: printf(“%-10s\n”,president); president scanf(“%s%d%s%d”, dept, &course_num, days, &time); A. Abhari CPS125

  24. #include <stdio.h> #define STRING_LEN 10 int main(void) { char dept[STRING_LEN]; int course_num; char days[STRING_LEN]; int time; printf("Enter department code, course number, days and "); printf("time like this:\n> COSC 2060 MWF 1410\n> "); scanf("%s%d%s%d", dept, &course_num, days, &time); printf("%s %d meets %s at %d\n", dept, course_num, days, time); return (0); } Enter department code, course number, days and time like this: > COSC 2060 MWF 1410 > MATH 1270 TR 1800 (scanf skips white space characters such blank MATH 1270 meets TR at 1800 newline and tab) A. Abhari CPS125

  25. Here names[i] is an array but ages[i] is int #define NUM_NAMES 30 #define NAME_LEN 25 …………….. char names [NUM_NAMES][NAME_LEN]; int ages [NUM_NAMES]; output parameters for (i=0; i<NUM_NAMES; ++i) { scanf(“%s%d”, names[i], &ages[i]; printf(“%-35s %d\n”, names[i], ages[i]); } input parameters A. Abhari CPS125

  26. String assignment char str[20]; str = “test” it is wrong, we can only use = in string initialization For doing that: # include <string.h> strcpy(str,”test”); after that strlen(str) returns 4 A. Abhari CPS125

  27. strcpy(destination, source) strcpy(one_str, “Test string 1”); Overwrites characters in destination with characters from source Stops at ‘\0’ in source • strlen(string) len = strlen(one_string); Returns the number of characters in string Does not include ‘\0’ A. Abhari CPS125

  28. String Comparison • ‘a’ < ‘b’ is true because the numeric code of ‘a’ is less than numeric code of character ‘b’ • But for strings it is not that easy, For example: thrill < throw is true because first non-matching characters at position three are compared joy < joyous is true because the first one is shorter, and all 3 initial characters of two strings match with each others • strcmp(string1, string2) Compares one string to another Returns < 0 if string1 < string2 0 if string1 == string2 > 0 if string1 > string2 A. Abhari CPS125

  29. Sentinel-controlled loop for string input 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 */ } A. Abhari CPS125

  30. 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 A. Abhari CPS125

  31. 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 A. Abhari CPS125

  32. 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 A. Abhari CPS125

  33. Dynamic Allocation of Arrays • In addition to stack heap is a second allocation storage area for specific requests while program is running. For example: a pointer variable in stack that points to double * nums_list; the start of dynamic array in heap determines array size in runtime num_lis = (double *) calloc(lsize, sizeof (double)); creates array elements that are initialized to zero finds the number of required bytes A. Abhari CPS125

  34. #include <stdio.h> #include <stdlib.h> /* gives access to calloc */ int main(void) { char *string1; int *array_of_nums; int str_siz, num_nums, i; printf("Enter string length and string> "); scanf("%d", &str_siz); string1 = (char *)calloc(str_siz, sizeof (char)); scanf("%s", string1); printf("\nHow many numbers?> "); scanf("%d", &num_nums); array_of_nums = (int *)calloc(num_nums, sizeof (int)); array_of_nums[0] = 5; for (i = 1; i < num_nums; ++i) array_of_nums[i] = array_of_nums[i - 1] * i; . . . free(string1); free(array_of_nums); Enter string length and string> 9 enormous How many numbers?> 4

  35. Common Programming Errors • Subscript range error with arrays • Applying & to the array name when array is used as an argument of a function is wrong even if array is output parameter but for using array elements as output parameters & is required • Note that int *z as formal parameter can be used both for array or an output int parameters • Overflow with strings in strcpy and scanf • Not considering the null character in string size • Intention to use dynamic array but forgetting calloc function A. Abhari CPS125

More Related