1 / 53

Arrays

Arrays. Why we need data structure ? Simple data types use a single memory cell to store a variable. Sometimes (for example scores of a class) it is more efficient to group data items together in main memory.

atalanta
Download Presentation

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 • Why we need data structure? • Simple data types use a single memory cell to store a variable. • Sometimes (for example scores of a class) it is more efficient to group data items together in main memory. • C allows to group related data items together into a single composite data structure. • Array is one such data structure. • Array => A collection of data items of the same type.

  2. Array x 2 4 7 9 1 x[4] x[0] x[1] x[2] x[3] Subscripted variable => x[0] Read as x sub zero. Declaring & Referencing Arrays • Array => collection of two or more adjacent memory cells (array elements). • To set up an array in memory, we must declare • - the name of the array and • - the number of cells associated with it. • int x[5]; Instructs the compiler to associate 5 memory cells with the name x array subscript

  3. Array Subscripts • Array subscript=> integer enclosed in brackets • => its value in the range: 0 - (array_size - 1). • Use of array subscript => to differentiate between the individual array elements. • => to specify which array element is to be manipulated. • We can use any expression of type int as an array subscript. • typedef enum • { monday, tuesday, wednesday, thursday,friday} • class_days_t; • int score[NUM_CLASS_DAYS]; Five class days

  4. 5 7 4 9 score [monday] 4 score [tuesday] score [wednesday] score [thursday] score [friday] Array subscript • typedef enum • { monday, tuesday, wednesday, thursday,friday} • class_days_t; • int score[NUM_CLASS_DAYS]; We can use enumeration constants monday through friday as array subscripts since the they are represented by the integers 0 through 4. array subscript array value

  5. Array Initialization • If there are fewer initializers than elements in the array, the remaining elements are automatically initialized to zero. • Example: int n[10] = {0}; • Note: Arrays are not automatically initialized to zero. • The programmer must at least initialize the first element to zero. • Initialize an array with declaration: • int odd_num[5] = {1, 3, 5, 7, 9}; • int odd_num[] = {1, 3, 5, 7, 9}; • Syntax error: • int n[5] = {3, 5, 7, 9, 11, 12} 5 array elements 6 initializers

  6. 0 1 8 27 64 Sequential Access • We can access the elements of an array in sequence by using an indexed for loop. • - Loop control variable runs from zero to one less than the array size. • - Loop counter is used as an array index(subscript) to access each element in turn. • Example: • int cube[5], i; • The for loop • for (i = 0; i < 5; ++i) • cube[i] = i * i * i; initializes this array :

  7. Compute the Sum and the Sum of the Squares of all Data • sum = x[0] +x[1] + x[2] + x[3] + x[4] + x[5] =  x[i]; • sum_sqr = x[0] 2 +x[1] 2+ x[2] 2+ x[3] 2+ x[4] 2+ x[5]2 =  x[i]2; • int i, sum = 0; • int sum_sqr = 0; • for (i = 0; i < MAX_ITEM; ++i) • { • sum += x[i]; or sum = sum + x[i]; • sum_sqr += x[i] * x[i]; or sum_sqr = sum_sqr + x[i] * x[i]; • }

  8. 2 4 7 9 1 Array Elements as Function Arguments Array x • #include <stdio.h> • main() • { • int x[5] = {2, 4, 7, 9, 1}; • int i; • printf(“The first element is: %d\n”, x[0]); • } • Another function: scanf(“%d”, &x[2]); Result: The first element is: 2 The scanned value will be stored in the array element x[2].

  9. Array as Function Arguments • We can also pass arrays as function arguments. • A array name with no subscript appears in the argument list of the function. • The address of the initial array element is stored in the function’s corresponding formal parameter. • Void fill_array ( int list[], // list of n integers • int n, // number of list elements • int in_value) // initial value • { • int i; • for ( i = 0; i < n; ++i) • list[i] = in_value; • }

  10. 1 1 1 1 1 Array as Function Arguments Function fill_array Data Area Calling function Data Area • Data Areas Before Return from fill_array(x, 5, 1). x list [0] [1] n [2] [3] in_value [4] i

  11. Array as Function Arguments • The function manipulates the original array, not its own personal copy. • So an assignment to one of the array elements by a statement in the function changes the contents of the original array. • list[i] = in_value; • ANSI C provides a qualifier const to notify the C compiler that • - the array is only an input to the function and • - the function should not be allowed to modify array elements. • - the elements of the array become constant in the function body. • - any attempt to modify an element of the array in the function body results in a compile time error. • Example: • int get_max(const int list[], // input- list of n integers • int n) // input- number of list elements

  12. Returning an Array Result • In C, it is not legal for a function’s return type to be an array. • It requires the use of an output parameter to send the result array back to the calling function. • Example: • void add_arrays(const int arg1[], // input • const int arg2[], // input • int argsum[], // output • int n) // input • { • for (i = 0; i < n; ++i) • argsum[i] = arg1[i] + arg2[i]; // adds corresponding elements // of arg1 and arg2 • }

  13. Why we apply Static to a Local Array Declaration? • We can apply static to a local array declaration so that • - the array is not created and initialized each time the function is called, and • - the array is not destroyed each time the function is exited in the program. • - this reduces program execution time particularly for programs with frequently called functions that contain large arrays.

  14. C + 2 Stacks • A stack is a data structure in which only the top element can be accessed. • Example: • A stack of plates in cafeteria. • A customer always takes the top plate. • When a plate is removed, the plate beneath it moves to the top. Stack of three characters Top of the stack Push => storing an item in a stack pop=> removing an item from a stack

  15. Function push • void push(char stack[], // input/output - the stack • char item, // input - data being pushed onto the stack • int *top, // input/output - pointer to top of stack • int max_size) // input - maximum size of stack • { • if (*top < max_size - 1) • { • ++(*top); • stack[*top] = item; • } • }

  16. Function Pop • Char pop(char stack[], // input/output - the stack • int *top) // input/output - pointer to top of stack • { • char item; // value popped off the stack • if (*top >= 0) • { • item = stack[*top]; • --(*top); • } • else • item = STACK_EMPTY; • return (item); • }

  17. C + 2 How to create a stack using Array? • Char s[STACK_SIZE]; • int s_top = -1; • The statements : • push(s, ‘2’, &s_top, STACK_SIZE); • push(s, ‘+’, &s_top, STACK_SIZE); • push(s, ‘C’, &s_top, STACK_SIZE); • create the stack : • pop(s, &s_top); • create the stack: + 2

  18. Searching an Array • We search an array to determine the location of a particular value (target). • Example: We need to search an array to determine the score of a particular student. • Two popular techniques: linear search and binary search • Linear search: • To search an array, first we need to know the array element value we are seeking ( target). • Then we have to examine each array element whether it matches the target by using a loop. • When the target is found, the search loop should be exited.

  19. Algorithm for Searching (Linear) an Array • Assume the target has not been found. • Start with the initial array element. • Repeat while the target is not found and there are more array elements • 4 if the current element matches the target • 5 Set a flag to indicate that the target has been found. • else • 6 Advance to the next array element. • if the target was found • 8 Return the target index as the search result. • else • 9 Return -1 as the search result.

  20. Function for Linear Searching of an Array • #define NOT_FOUND -1 • int search(const int arr[], int target, int n) • { • int i = 0, found = 0, where; • while (!found && i < n) // Compare each element to target • { • if (arr[i] == target) • found = 1; • else • ++i; • } • if (found) // Returns index of element matching target or • where = i; // NOT_FOUND • else • where = NOT_FOUND; • return (where); • }

  21. Binary Search • The binary search algorithm eliminates on ehalf of the elements in the array being searched after each comparison. • The algorithm locates the middle element of the array and compares it to the target. • If they are equal, thetarget is found and the array subscript of that element is returned. • If they are not equal, the problem is reduced to searching one half of the array. • If the target is less than the middle element of the array, the first half of the array is searched. • Otherwise the second half of the array is searched. • If the target is not found in the specified subarray, the algorithm is repeated on one quarter of the original array. • The search continues until the target is equal to the middle element of a subarray, or until the subarray contains one element that is not equal to the target.

  22. Function for Binary Searching of an Array • int binarySearch( int list[], int target, int low, int high ) • { • int middle; • while ( low <= high ) • { • middle = ( low + high ) / 2; • if ( target == list[middle] ) • return middle; • else if ( target < list[middle] ) • high = middle - 1; • else • low = middle + 1; • } • return -1; • }

  23. Comparison of Linear and Binary Search • Linear search compares each element of the array with the target. On average , therefore the program will compare the target with half of the elements of the array. • Linear search works well for small arrays or for unsorted arrays. However, for large arrays linear searching is inefficient. • For a large and sorted array, the high speed binary search technique can be used. • In a worst case scenario, searching in an array of 1024 elements will take only 10 comparisons using a binary search. A array of one billion elements takes a maximum of 30 comparisons to find the target. • 2 10 = 1024 1000 • 2 30 = 1024 * 1024 * 1024 1000000000

  24. Sorting an Array • Many program executes more efficiently if the data are sorted before processing. • Example: You grade reports can be sorted according your student ID numbers. A bank sorts all checks by account number. • Selection sort is a fairly simple but not very efficient.sorting algorithm. • To perform a selection sort of an array of n elements, first you have to locate the smallest element in the array. • Then switch the smallest element with the element at subscript 0. • Then locate the smallest element remaining in the subarray with subscripts 1 through n -1. • Then switch the the smallest (second smallest) element in the second position. • And so on.

  25. Algorithm for Selection Sort • for each value of fill from 0 to n -2 • 2 Find index_of_min, the index of the smallest element in the unsorted subarray list[fill] through list[n -1]. • 3 if fill is not the position of the smallest element (index_min) • 4 Exchange the smallest element with the one at position fill.

  26. Function select_sort • int get_min_range (int list[], int first, int last); • void select_sort (int list[], int n) • { • int fill, temp, index_of_min; • for (fill = 0; fill < n -1; ++fill) • { • index_of_min = get_min_range(list, fill, n -1); • if (fill != index_of_min) • { • temp = list[index_of_min]; • list[list_of_min] = list[fill]; • list[fill] = temp; • } • } • }

  27. 74 45 83 16 16 45 83 74 16 45 83 74 16 45 74 83 Selection Sort Fill is 0. Find the smallest element in subarray list[0] through list[3] and swap it with list[0] • Trace of selection sort Fill is 1. Find the smallest element in subarray list[1] through list[3] - no exchange needed. Fill is 2. Find the smallest element in subarray list[2] through list[3] and swap it with list[2].

  28. O O X X X O O X X Multidimensional Array • Multidimensional array => array with two or more dimensions. • We use two dimensional arrays to represent tables of data, matrices, and other two-dimensional objects. • A two dimensional object is a tic-tac-toe board. • The array declaration: char tictactoe[3][3]; or char tictactoe[][3]; • The array initialization: • char tictactoe [3][3] = {{‘ ‘, ‘ ‘, ‘ ‘}, {‘ ‘, ‘ ‘, ‘ ‘}, {‘ ‘, ‘ ‘, ‘ ‘}}; Column tictactoe[0][2] 0 1 2 0 1 Row 2

  29. Array with Several Dimensions Used to store the enrollment data for a school. course campus year • int enroll [MAXCRS][5][4] Problem: College offers 100 (MAXCRS) courses at five different campuses. We numbered the freshman year 0, the sophomore year 1, and so on. Find the number of juniors in all classes at all campuses. Students will be counted once for each course in which they are enrolled. int i, j, num_junior; // number of juniors num_junior = 0; for ( i = 0; i < MAXCRS; ++i) for ( j = 0; j < 5; ++j) num_junior += enroll[i][j][2];

  30. Strings • String is a data structure. • String is a series of characters treated as a single unit. • A string may include letters, digits, and various special characters such as +, -, *, /, $, and others. • String literal or string constants in C are written in double quotation marks as “Daniel Boles”. • printf or scanf uses a string constant as the first argument. • printf (“”Sum = %.3f”, sum); • scanf(“%s”, word);

  31. Why strings are important ? • Many computer applications are concerned with the manipulation of textual data rather than numerical data. • Computer-based word processing systems enable a user to compose letters, term papers, newspaper articles, and books. • Chemist works with elements and compounds whose names often combine alphabetic and numeric characters (e.g., C12 H22O11). • Many mathematicians, physicists, and engineers use strings of characters and numeric data.

  32. [1] [2] [3] [4] [0] b l u e \0 Declaring and initializing String Variables • C implements the string data structure using either a character array or a variable of type char *. • char color[] = “blue”; // creates a 5-element array color containing characters ‘b’, ‘l’, ‘u’, ‘e’, and ‘\0’. • char *colorPtr = “blue”; // creates pointer variable colorPtr that points to the string “blue” somewhere in memory. • Both declarations initialize a variable to the string “blue”. Color in memory after this declaration and initialization. Null character that marks the end of a string.

  33. scanf • A string can be assigned to an array using scanf. • char word[20]; • scanf(“%s”, word); // The string entered by the user is stored in word. • Function scanf will read characters until a space, newline, or end-of-file indicator is encountered. • When it comes across a whitespace character, scanning stops, and scanf places the null character at the end of the string of the string. word is an array which is a pointer. So the & is not needed with argument word.

  34. [1] [2] [3] [4] [0] c h e m i scanf • When the scanf function is scanning a string, if there is more input data (with no blanks) than will fit in the array output argument, scanf copies in the whole string overflowing the output argument because scanf has no way of knowing the array’s declared size. • char dept[7]; // Note that the string should be no longer than 6 characters to leave space for the terminating NULL character. • scanf(“%s”, dept); If the data entered as chemistry: • For a character array to be printed as a string , the array must contain a terminating NULL character. Space not allocated for dept [6] [7] [8] [9] [5] s t r y \0

  35. Arrays of Strings • A string is an array of characters. • An array of strings is a two-dimensional array of characters in which each row is one string. • #define NUM_DAY 7 • #define NAME_LEN 20 • char days[NUM_DAY][NAME_LEN]; To declare an array days to store 7 days, each of which is less than 20 characters long. char days[7[20] = {“Sunday”, “Monday”, “Tuesday”,“Wednesday”, “Thursday”, “Friday”, “Saturday”};

  36. String Assignment • We do use the assignment symbol in a declaration of a string variable with initialization, this context is the only one in which the operator means to copy the string (right operand) into the variable (left operand). • Example: • char str[20] = “Initial Value”; // valid • str = “Initial Value”; // invalid • Array name with no subscript represents the address of the initial array element. • This address cannot be changed through assignment. • So the last line will cause a compiler error message such as Invalid target of assignment:

  37. String Assignment • C provides the string assignment operations through library functions. • The library string.h provides functions for substring, concatenation, string length, string comparison, etc. • Some selected string library functions: • strcpy => makes a copy of source, a string, in the character array. • Strcpy(s1, “hello”); • strcat => Appends source to the end of dest. • Strcat(s1, “and Physics”); • strcmp => compares s1 and s2 alphabetically, and returns • a negative value if s1 precedes s2, • a zero if the strings are equal, • a positive value if s2 precedes s1.

  38. Space not allocated for dept [6] [7] [8] [9] [5] s t r y \0 [1] [2] [3] [4] [0] c h e m i strcpy • When the strcpy function is copying a string, if there is more input data than will fit in the destination variable (dept), strcpy copies in the whole string (second argument) overflowing the dept . • char dept[7]; // Note that the string should be no longer than 6 characters to leave space for the terminating NULL character. • strcpy(dept, “chemistry”); would overflow dept storing the final characters ‘r’, ‘y’, and ‘\0’ in memory allocated for other variables. • The values of these other variables would change spontaneously.

  39. [1] [1] [2] [2] [3] [3] [4] [4] [0] [0] [6] [6] [5] [5] M C h a t e m h \0 i s \0 \0 t strncpy • Another string-copying function is strncpy. • It takes source, destination, and the number of characters to be copied. • It does not add a null character. • If the string to be copied is shorter than n characters, the remaining characters stored are null.Example: strncpy(dept, “Math”); • When the source string is longer than n characters, only the first n characters are copied. Example: Strncpy(dept, “Chemistry”); Prevents overflow. It has not stored a valid string in dept.

  40. strncpy • To prevent overflow of destination string and • to prevent an invalid string stored in dept • One can assign as much as will fit of a source string to a destination of length dest_len by using the statements: • strncpy(dest, source, dest_len - 1); // prevents overflow • dest[dest_len - 1] = ‘\0’; // valid string

  41. Substrings • W need to reference a substring of a longer string. • char last[20], first[20], middle[20], middle[20]; • char pres[20] = “Adam, John Quincy”; srtncpy(last, pres, 5); last[5] = ‘\0’; Strcpy(middle, &press[12]); strncpy(first, &press[7], 4); first[4] = ‘\0’;

  42. Longer String: String Concatenation • Function strcat appends its second argument, a string to its first argument, a character array containing a string. • The first character of the second argument replaces the NULL (‘0’) that terminates the string in the first argument. • The programmer must ensure that the array used to store the first string is large enough to store the first string, the second string, and the terminating NULL character. • char f1[15] = “John”, f2[15] = “Jacqueline”, • last [15] = “Kennedy”; • strcat(f1, last); • strcat(f2, last) // invalid overflow of f2

  43. Longer String: String Concatenation • Two critical questions: • - Is there enough space in the output parameter for the entire string being created? • - Does the created string end in ‘\0’? • if (strlen(s1) + strlen(s2) < STRSIZ) // function strlen returns the • { // value of its string argument. • strcat(s1, s2); // it does not count the ‘\0’ • } • else • { • strncat(s1, s2, STRSIZ - strlen(s1) - 1); • s1[STRSIZ - 1] = ‘\0’; • }

  44. Difference between a character & a string • Difference between the internal representations of the character ‘P’ and the string “P”. P P \0 ? ? ? ? ? ….. character ‘P’ string “P”

  45. String Comparison • Characters are represented by numeric codes. • We use relational and equality operator to compare characters. • Example: • ch1 < ch2 is used to test character variables in decision statements. • We cannot use the operator to compare strings because in C, strings are represented by arrays. • str1 < str2 it is not checking whether str1 precedes str2 alphabetically. • It determines whether the place in memory where storage of str1 begins precedes the place in memory where str2 begins. • str1 and str2 represent the addresses of the initial elements of arrays str1 and str2.

  46. String Comparison • Ch1 < ch2 is true if the numeric character code value of ch1 is less than the code in ch2. • ANSI C extends this concept to strings by stating the following two conditions to define “less than” • If the first n characters of str1 and str2 match and str1[n], str2[n] are the first nonmatching corresponding characters, str1 is less than str2 if str1[n] < str2[n]. • str1 step • str2 stop • If str1 is shorter than str2 and all the characters of str1 match the corresponding characters of str2, str1 is less than str2. • str1 harm • str2 harmful First 2 letters match. str1[2] < str2[2] since ‘e’ < ‘o’

  47. strcmp • Strcmp(str1, str2) returns • - negative integer if str1 is less than str2. • Example: str1 “carrot” • str2 “spinach” • - zero if str1 equals str2. • Example: str1 “carrot” • str2 “carrot” • - positive integer if str1 is greater than str2. • Example: str1 “spinach” • str2 “carrot”

  48. strncmp • strncmp(str1, str2, n) compares only the first n characters of the two strings. • Example: str1 “strength” • str2 “string” • strncmp(str1, str2, 3) returns • - zero because “str”matches “str” • strncmp(str1, str2, 4) returns • - negative integer because “stre” precedes “stri” alphabetically.

  49. Example of array of pointers • Multiple ordering of a list of strings can be maintained by storing the strings once and creating arrays of pointers for additional ordering. • The original list is a list of names in which applications were received. • Names is an array of pointers through which the list can be accessed in alphabetical order. • Each pointer points to the first character of its corresponding string. original names[0] ‘J’ ‘o’ ‘h’ ‘n’ ‘\0’ names[1] ‘C’ ‘y’ ‘n’ ‘t’ ‘h’ ‘i’ ‘a’ ‘\0’ names[2] ‘D’ ‘a’ ‘v’ ‘i’ ‘d’ ‘\0’ names[3] ‘B’ ‘a’ ‘r’ ‘b’ ‘a’ ‘r’ ‘a’ ‘\0’

  50. Character Handling Library • The ctype library provides functions for classification and conversion of single characters. • Example: • function isdigit determines whether its argument is a digit (0-9). • function isalpha determines whether its argument is an uppercase letter (A-Z) or a lower case letter (a-z). • Function islower determines whether its argument is a lowercase letter (a-z). • Function isupper determines whether its argument is an uppercase letter (A-Z). • Function tolower converts an uppercase letter to a lowercase letter. • Function toupper converts an lowercase letter to an uppercase letter.

More Related